<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------


/**
 * 店铺操作类 xShopHandler
 * @package  htdocs
 * @subpackage  module/base
 * @create by allen.qiang
 * @version 1.0
 */

quanli_include ('module/base/messageHandler.class.php');
quanli_include ('module/base/billHandler.class.php');
quanli_include ('module/base/customerHandler.class.php');
quanli_include ('module/base/systemHandler.class.php');
quanli_include ('module/base/goodsHandler.class.php');
quanli_include ('module/base/promotionHandler.class.php');
quanli_include ('module/base/logHandler.class.php');

define('TBPAY' , 30) ;		//支付宝
define('QQPAY' , 31) ;		//财付通
define('EXTPAY' , 40) ;		//第三方支付方式号	
define('DELIVERID' , 8) ;	//默认配送方式


class xShopHandler {
    private $dbca;
    
    public function __construct(&$dbca) {
        $this->dbca = $dbca;
    }
	
 	/**
 	 * 执行消息订阅
 	 *
 	 * @param unknown_type $params 请求参数			
 	 * @param unknown_type $isSync true 代表异步 false 代表同步结果直接返回 
 	 * @return unknown
 	 */
	public function pushMQ($params , $isSync = false){
		$msgHandler = new messageHandler() ;
		$signParams = $msgHandler->sign($params) ;
		return  $msgHandler->push($signParams , $isSync) ;
	}
	
    /**
	 * 异步回调处理
	 *
	 * @param unknown_type $params	参数
	 */
	public function callMQ($params){
		global $G_PGLOB;

		$fun  = $params['message'] ;			//函数名称
		$data = $params['data'] ;				//数据格式
		
		//异步回调处理
		switch ($fun) {
			case  'sys_trades' :
				//系统自己执行取订单
				$startTime = $data['startTime'] ;			//请求开始时间
				$endTime   = $data['endTime'] ;				//执行结束时间
				$finishTime= $data['finishTime'] ;			//请求结束时间
				$pageIndex = $data['pageIndex'] ;			//当前页码
				$shopID	   = $data['shopID'];				//店铺号
				
				//查询店铺信息
				$shopArr = array('shopID' => $shopID , 
								 'useFlg' => 1) ;
				//店铺参数		
				$shopInfo = $this->shopList($shopArr) ;
				if(!$shopInfo) {
					die();
				}
				
				$shopInfo 	= $shopInfo[0] ;
				$trade_data = isset($data['tradeList']['trades']) ? $data['tradeList']['trades'] : null;										//淘宝订单数据
				$shopCode 	= $shopInfo->shopCode ;
				
				//循环格式化订单数据
				if($trade_data){	
					$has_next     = isset($data['tradeList']['has_next']) ? $data['tradeList']['has_next'] : false ; 				//是否存在下一页
					$lastModified = $data['tradeList']['modified'] ;																//最后修改时间
																			
					//保存请求日志
					$request_arr = array( 'start_date'=> $startTime ,
										  'end_date'  => $endTime ,
										  'pageIndex' => $pageIndex) ;
					//请求参数					    			  
					$params = array(  'creator' 	 => 'system' ,
									  'request_str'  => print_r($request_arr , true) ,
									  'response_str' => print_r($trade_data , true) ,
									  'request_flg'  => 1, 
									  'request_type' => 1,
									  'shopID'	 	 => $shopID) ;
									  
					$req_no = $this->saveTradesLog($params) ;				  
						
					//循环保存交易			  
					$billObj = new billHandler($G_PGLOB->DBCA);	

					foreach($trade_data as &$t_d){
						try{
							//取天猫订单号
							$tid = number_format($t_d['tid'] , 0 , '' , '') ;
							
							//检查订单是否已经存在
							$tradeReq = array('order_id' => $tid , 
											  'shopID' 	 => $shopID , 
											  'rp' 		 => 0) ;
							$issetTrade = $this->trade3rdList($tradeReq) ;
							
							if($issetTrade){
								continue ;
							}
							
							//格式化订单
							$billArray = $this->TBtradeFormat($shopID , $shopCode , $t_d) ; 
							if($billArray['code'] != 200){
								throw new Exception($billArray['message']) ;
							}
							
							//保存订单
							$billMesg = $billObj->save3rdBill($billArray['message']) ;
							if($billMesg['code'] != 200){
								throw new Exception($billMesg['message']) ;
							}
							
							$bill_no 	= $billMesg['data']['bill_no'] ;
							$bill_index = $bill_no . $billArray['message']['pcustID'];

				            //保存订单信息到redis
				            $G_PGLOB->sessionCache_set('bill_' . $bill_index, $billArray['message'] , 0 , true);
				
				            $billMessage = array(
				                'action'  => 'bill',
				                'operFlg' => 1,
				                'params'  => array(
				                    $bill_index
				                )
				            );
				            sendMessageMq($billMessage,1);
							
				            //保存订单和交易关系							
							$nickname 	= $billArray['message']['buyer_nick'] ;
							$buyer_msg	= $billArray['message']['master']['remark'] ;
							$seller_msg = $billArray['message']['vender_remark'] ;
							$pay_time	= $billArray['message']['pay_time'] ;
						            
						    $this->save_trades_rel($shopID , $bill_no , $tid , $nickname , $pay_time , $buyer_msg , $seller_msg) ;
						  
						}catch (Exception $e){
							//保存错误信息
							$params = array ( 'creator'  => 'system',
											  'req_no' 	 => $req_no ,
											  'order_id' => $tid,
											  'err_msg'  => $e->getMessage() ,
											  'shopID' 	 => $shopID ,
											  'action'   => 0 ) ;
							$this->saveTradesFail($params) ;
						}
					}
					
					//更新订单最后修改时间
					$this->updateLastInfo($lastModified , $pageIndex , $shopID , 1) ;
				}

				$days = $this->diffDays($startTime , $endTime) ;
				
				if($days > 1 && $endTime == $finishTime){
					//传入的时间段大于24小时将分段传入
					$end_str = strtotime($startTime) + 86400 ;
					$endTime = date('Y-m-d H:i:s' , $end_str) ;
					
					$reqArray = array('code'	=> 100,
									  'data' 	=> array() , 
									  'message' => 'sys_trades') ;
									  
					$reqArray['data']['startTime'] = $startTime ;
					$reqArray['data']['endTime']   = $endTime ;
					$reqArray['data']['finishTime']= $finishTime ;
					$reqArray['data']['pageIndex'] = $pageIndex ;	
					
					$reqArray['data']['appkey']	   = $shopInfo->appkey ;
					$reqArray['data']['secret']	   = $shopInfo->secret ;
					$reqArray['data']['sessionkey']= $shopInfo->sessionkey ;
					$reqArray['data']['shopName']  = $shopInfo->shopName ;
					$reqArray['data']['userID']    = $shopInfo->userID ;
					$reqArray['data']['shopID']    = $shopID ;
					
					$this->pushMQ($reqArray);
				}else if($endTime != $finishTime && $has_next== true){
					//采用分段后是否还存在下一面，如果有传入页的页码
					$reqArray = array('code'	=> 100, 
									  'data' 	=> array() , 
									  'message' => 'sys_trades') ;
									  
					$reqArray['data']['startTime'] = $startTime ;
					$reqArray['data']['endTime']   = $endTime ;
					$reqArray['data']['finishTime']= $finishTime ;
					$reqArray['data']['pageIndex'] = $pageIndex+1 ;	
					
					$reqArray['data']['appkey']	   = $shopInfo->appkey ;
					$reqArray['data']['secret']	   = $shopInfo->secret ;
					$reqArray['data']['sessionkey']= $shopInfo->sessionkey ;
					$reqArray['data']['shopName']  = $shopInfo->shopName ;
					$reqArray['data']['userID']    = $shopInfo->userID ;
					$reqArray['data']['shopID']    = $shopID ;
					
					$this->pushMQ($reqArray);
				}else if($endTime != $finishTime && $has_next== false){
					//如果本次分段结束后采用结束时间传给开时间
					$reqArray = array('code'	=> 100, 
									  'data' 	=> array() , 
									  'message' => 'sys_trades') ;
									  
					$reqArray['data']['startTime'] = $endTime ;
					$reqArray['data']['endTime']   = $finishTime ;
					$reqArray['data']['finishTime']= $finishTime ;
					$reqArray['data']['pageIndex'] = 1 ;	
					
					$reqArray['data']['appkey']	   = $shopInfo->appkey ;
					$reqArray['data']['secret']	   = $shopInfo->secret ;
					$reqArray['data']['sessionkey']= $shopInfo->sessionkey ;
					$reqArray['data']['shopName']  = $shopInfo->shopName ;
					$reqArray['data']['userID']    = $shopInfo->userID ;
					$reqArray['data']['shopID']    = $shopID ;
					
					$this->pushMQ($reqArray);
					
				}else if($endTime == $finishTime && $has_next== true){
					//调度时间小于24小时正常调试
					$reqArray = array('code'	=> 100, 
									  'data' 	=> array() , 
									  'message' => 'sys_trades') ;
									  
					$reqArray['data']['startTime'] = $startTime ;
					$reqArray['data']['endTime']   = $endTime ;
					$reqArray['data']['finishTime']= $finishTime ;
					$reqArray['data']['pageIndex'] = $pageIndex+1 ;	
						
					$reqArray['data']['appkey']	   = $shopInfo->appkey ;
					$reqArray['data']['secret']	   = $shopInfo->secret ;
					$reqArray['data']['sessionkey']= $shopInfo->sessionkey ;
					$reqArray['data']['shopName']  = $shopInfo->shopName ;
					$reqArray['data']['userID']    = $shopInfo->userID ;
					$reqArray['data']['shopID']    = $shopID ;
					
					$this->pushMQ($reqArray);
				}else{
					die();
				}
			break ;

		}
	}
	
	/**
	 * 更新交易最后修改取的时间
	 *
	 * @param unknown_type $start_modified
	 * @param unknown_type $pageIndex
	 * @param unknown_type $sourceFlg
	 */
	public function updateLastInfo ($modified , $pageIndex , $shopID , $type) {
		$this->dbca->stmt_query ('UPDATE 3rd_last_info SET timeStamp=NOW() ,modified=?,pageIndex=? WHERE shopID=? AND type=?' , 'siii', $modified , $pageIndex , $shopID , $type);
	}
	
	/**
	 * $params = array (creator   => '' ,
	 * 					req_no	  => '',
	 * 					order_id  => '' ,
	 * 					bill_no	  => '',
	 * 					err_msg   => '' ,
	 * 					shopID    => '',
	 * 					action	  => ) ;
	 *
	 * @param unknown_type $params 订单请求失败表
	 */
	public function saveTradesFail($params) {
		if(isset($params['creator'] , $params['req_no'] , $params['order_id'] , $params['bill_no'] , $params['err_msg'] , $params['shopID'] , $params['action'])){
			$trades_fail = new entity('3rd_trades_fail') ;
			$trades_fail -> creator  = $params['creator'] ;
			$trades_fail -> req_no   = $params['req_no'] ;
			$trades_fail -> order_id = $params['order_id'] ;
			$trades_fail -> bill_no  = $params['bill_no'] ;
			$trades_fail -> err_msg  = $params['err_msg'] ;
			$trades_fail -> shopID   = $params['shopID'] ;
			$trades_fail -> action   = $params['action'] ;
			$this->dbca->save($trades_fail ,'3rd');
		}
	}
	
	/**
	 * $params = array (creator 	 => 'system' ,
	 * 					request_str	 => '',
	 * 					response_str => '' ,
	 * 					request_flg	 => '',
	 * 					request_type => '' ,
	 * 					shopID	 	 => '' ) ;
	 *
	 * @param unknown_type $params 订单请求日志表
	 */
	public function saveTradesLog ($params) {
		if(isset($params['creator'] , $params['request_str'] , $params['response_str'] , $params['request_flg'] , $params['request_type'] , $params['shopID'])){
			$bill_log = new entity('3rd_trades_log') ;
			$bill_log -> creator 	  = $params['creator'] ;
			$bill_log -> request_str  = $params['request_str'] ;
			$bill_log -> response_str = $params['response_str'] ;
			$bill_log -> request_flg  = $params['request_flg'] ;
			$bill_log -> request_type = $params['request_type'] ;
			$bill_log -> shopID  	  = $params['shopID'] ;
			$this->dbca->save($bill_log ,'3rd');
			return $this->dbca->insert_id ;
		}
		return null ;
	}
	
	//第三方交易列表
	public function trade3rdList(&$params) {
		//sql字符串
        $sql = '';
        //参数类型字符串
        $params_type = '';
        //参数值数组
        $params_array = array();
        //交易号
        if (isset($params['order_id']) && !empty($params['order_id'])) {
            $sql .= ' AND tr.order_id = ?';
            $params_type .= 's';
            $params_array[] = $params['order_id'];
        }

        //订单号
        if (isset($params['bill_no']) &&  !empty($params['bill_no']) ) {
            $sql .= ' AND tr.bill_no = ?';
            $params_type .= 's';
            $params_array[] = trim($params['bill_no']);
        }

        //店铺
        if (isset($params['shopID']) && !empty($params['shopID'])) {
            $sql .= ' AND tr.shopID = ?';
            $params_type .= 's';
            $params_array[] = $params['shopID'];
        }

        //下单时间
        if (!empty($params['startDate']) && !empty($params['endDate'])) {
            $sql .= ' AND tr.createTime >= ?  AND tr.createTime <= ?';
            $params_type .= 'ss';
            $params_array[] = $params['startDate'] . ' 00:00:00';
            $params_array[] = $params['endDate'] . ' 23:59:59';
        }
        
        //交易状态
        if (!empty($params['status'])) {
            $sql .= ' AND tr.status = ?  ';
            $params_type .= 'i';
            $params_array[] = $params['status'];
        }
        //交易类型
        if (!empty($params['tdType'])) {
        	$sql .= ' AND tr.trade_type = ?  ';
        	$params_type .= 'i';
        	$params_array[] = $params['tdType'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        //分页字符串
        $limit = '';

        if (isset($params['rp']) && $params['rp'] > 1) {

            //排序
            if (isset($params['sortname']) && !empty($params['sortname']))
                $limit .= sprintf(' ORDER BY tr.%s %s', $params['sortname'], $params['sortorder']);

            //分页
            if (!isset($params['page']) || !is_numeric($params['page']) || $params['page'] <= 0)
                $params['page'] = 1;

            $limit .= sprintf(' LIMIT %d, %d', ($params['page'] - 1) * $params['rp'], $params['rp']);
			
             //统计数量
	        $count_sql = 'SELECT COUNT(*) AS num FROM 3rd_trades tr LEFT JOIN `3rd_shop` sp ON tr.shopID=sp.shopID ' . $sql;
	        $count_arr = $this->dbca->stmt_query($count_sql , $params_type , $params_array);
			$params['count'] = $count_arr[0]->num ;
			
        } else {
            //排序
            if (isset($params['sortname']) && !empty($params['sortname']))
                $limit .= sprintf(' ORDER BY tr.%s %s', $params['sortname'], $params['sortorder']);
        }

        //查交易信息
        $search_sql = 'SELECT tr.*, sp.title FROM 3rd_trades tr INNER JOIN 3rd_shop sp ON tr.shopID=sp.shopID ' . $sql . $limit;
        $result_all = $this->dbca->stmt_query($search_sql, $params_type, $params_array);
		return $result_all ;
	}
	
	/**
	 * 保存第三方会员和官网会员对应关系
	 *
	 * @param unknown_type $custID			//会员名称
	 * @param unknown_type $pcustID			//会员号
	 * @param unknown_type $buyer_nick		//第三方会员名称
	 * @param unknown_type $shopID			//店铺号
	 */
	public function save_3rdCust_rel($custID , $pcustID , $buyer_nick , $shopID){
		$save_3rd_customer = new entity('3rd_customer_relation');
		$save_3rd_customer->creator  = 'system' ;
		$save_3rd_customer->custID   = $custID ;
		$save_3rd_customer->pcustID  = $pcustID ;
		$save_3rd_customer->userName = $buyer_nick ;
		$save_3rd_customer->shopID   = $shopID ;
		$this->dbca->save($save_3rd_customer,'3rd');
	}
	
	/**
	 * 保存第三方交易
	 *
	 * @param unknown_type $shopID		店铺号
	 * @param unknown_type $bill_no		订单号
	 * @param unknown_type $order_id	交易号
	 * @param unknown_type $nickname	别名
	 * @param unknown_type $pay_time	支付时间
	 * @param unknown_type $buyer_ms	买者留言
	 * @param unknown_type $seller_msg	商家留言
	 */
	public function save_trades_rel($shopID , $bill_no , $order_id , $nickname , $pay_time , $buyer_msg , $seller_msg , $applier_id = '' , $applier_nick = '' , $trade_type = 1) {
		$save_trades = new entity('3rd_trades') ;
		$save_trades->creator     = 'system' ;
		$save_trades->bill_no     = $bill_no ;
		$save_trades->order_id    = $order_id ;
		$save_trades->nickname    = $nickname ;
		$save_trades->buyer_memo  = $buyer_msg;
		$save_trades->seller_memo = $seller_msg;
		$save_trades->status 	  = 1;
		$save_trades->payTime 	  = $pay_time;
		$save_trades->applier_id  = $applier_id;
		$save_trades->applier_nick= $applier_nick;
		$save_trades->trade_type  = $trade_type;
		$save_trades->shopID 	  = $shopID;
		$this->dbca->save($save_trades,'3rd') ;	
	}
	
	//根据商品外部编码得到网站商品信息
	public function get_trades_goods($goodsCode){
		//查询官网商品信息
		$goodsInfo = $this->dbca->stmt_query('SELECT * FROM `goods_sale_edit` WHERE product_code=?' , 's' ,$goodsCode) ;
		if(!$goodsInfo){
			$goodsInfo = $this->dbca->stmt_query('SELECT gs.* FROM goods_sale_edit gs INNER JOIN `goods_code` gc WHERE gs.`product_code` = gc.`product_code` AND gc.`goodsCode`=? ' , 's' ,$goodsCode) ;
		}
		return $goodsInfo ;
	}
	
	/**
	 * 得到时间相差的天数
	 *
	 * @param unknown_type $startTime		开始时间
	 * @param unknown_type $endTime			结束时间
	 * @return unknown
	 */
	private function diffDays($startTime , $endTime){
		$diffStr = strtotime($endTime) - strtotime($startTime) ; //得到时间差
		return ceil($diffStr / 86400) ;						 	 //得到向下取整的天数
	}
	
    /**
     * @param 保存店铺信息
     */
    public function saveShop($shopArray){
        if(!isset($shopArray['channel'] , $shopArray['title'], $shopArray['useFlg'])){
            return  array('code' => 400 , "message" => '错误参数');
        }
        
        $msg = '' ;
        if(empty($shopArray['title'])){
            $msg .= '店铺标题不能为空<br/>';
        }
        if(!isset($shopArray['channel'])){
            $msg .= '店铺渠道不能为空<br/>';
        }

        if($msg != ""){
        	return  array('code' => 400 , 'message' => $msg);
        }
        
        if($shopArray['shopID'] == '' || $shopArray['shopID'] == 0){
        	//判断店铺是否已经存在
            $saveShop=new entity("3rd_shop");
            $saveShop->channel  = $shopArray['channel'];
            $saveShop->title 	= $shopArray['title'];
            if($this->dbca->fetch($saveShop)){
            	return  array('code' => 400 , 'message' => '店铺已经存在');
            }	
            //保存店铺	
			$saveShop->title 	= isset($shopArray['title']) && $shopArray['title'] != ''? $shopArray['title'] : $shopArray['shopName'];
			//$saveShop->userID 	= isset($shopArray['userID']) ? $shopArray['userID'] : null;
			$saveShop->shopdesc = isset($shopArray['shopdesc']) ? $shopArray['shopdesc'] : null;
			$saveShop->password = isset($shopArray['password']) ? $shopArray['password'] : null;
			$saveShop->appkey 	= isset($shopArray['appkey']) ? trim($shopArray['appkey']) : null;
			$saveShop->secret 	= isset($shopArray['secret']) ? trim($shopArray['secret']) : null;
			$saveShop->identity = isset($shopArray['identity']) ? trim($shopArray['identity']) : null;
			$saveShop->isMall 	= isset($shopArray['isMall']) ? trim($shopArray['isMall']) : null;
			$saveShop->creator  = $shopArray['creator'];
			$saveShop->sessionkey = isset($shopArray['sessionkey']) ? trim($shopArray['sessionkey']) : null;
			$saveShop->useFlg   = $shopArray['useFlg'];
            $this->dbca->save($saveShop , '3rd');
            
            return  array('code' => 200 , 'message' => '店铺已保存');
        }else{
        	//判断店铺是否已经存在
            $issetShop = $this->dbca->stmt_query('SELECT * FROM 3rd_shop WHERE title=? AND shopID!=? ','ss', $shopArray['title'] , $shopArray['shopID']);
            if($issetShop){
            	return  array('code' => 400 , 'message' => '店铺已经存在');
            }
           	//更新店铺
           	$updateShop = new entity("3rd_shop");
			$updateShop->shopID  = $shopArray['shopID'];
			if($this->dbca->fetch($updateShop)){
				$updateShop->channel  = $shopArray['channel'];
				$updateShop->shopName = isset($shopArray['shopName']) ? $shopArray['shopName'] : null;
				$updateShop->title 	  = isset($shopArray['title']) && $shopArray['title'] != '' ? $shopArray['title'] : $shopArray['shopName'];
				//$updateShop->userID   = isset($shopArray['userID']) ? $shopArray['userID'] : null;
				$updateShop->shopdesc = isset($shopArray['shopdesc']) ? $shopArray['shopdesc'] : null;
				$updateShop->password = isset($shopArray['password']) ? $shopArray['password'] : null;
				$updateShop->appkey   = isset($shopArray['appkey']) ? trim($shopArray['appkey']) : null;
				$updateShop->secret   = isset($shopArray['secret']) ? trim($shopArray['secret']) : null;
				$updateShop->identity = isset($shopArray['identity']) ? trim($shopArray['identity']) : null;
				$updateShop->isMall   = isset($shopArray['isMall']) ? trim($shopArray['isMall']) : null;
				$updateShop->useFlg   = $shopArray['useFlg'];
				$updateShop->sessionkey = isset($shopArray['sessionkey']) ? trim($shopArray['sessionkey']) : null;
				$this->dbca->save($updateShop , '3rd');
				return  array('code' => 200 , 'message' => '店铺已更新');
			}
        }
    }
    
    /**
     * 删除店铺信息
     */
    public function deleteShop($params){
    	if(!isset($params['shopID'])){
    		return  array('code' => 400 , "message" => '错误参数');
    	}
    	//店铺号
        $shopID = $params['shopID'] ;
        $this->dbca->stmt_query('DELETE FROM 3rd_shop WHERE shopID=?','s',$shopID);
        return array('code' => 200, 'message' => "已删除店铺");
    }
    
	//查询店铺信息
    public function shopList($arg_array){
         //sql字符串
        $sqlStr = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //店铺号
        if (isset($arg_array['shopID']) && !empty($arg_array['shopID'])) {
            $sqlStr .= ' AND s.shopID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['shopID'];
        }

        //渠道ID
        if (isset($arg_array['channel']) && !empty($arg_array['channel'])) {
            $sqlStr .= ' AND s.channel = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['channel'];
        }
        
        //使用标志
        if (isset($arg_array['useFlg']) && !empty($arg_array['useFlg'])) {
            $sqlStr .= ' AND s.useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }
        
		if ($sqlStr) {
			$sqlStr = ' WHERE ' . substr($sqlStr, 4);
		}
		
        //查询店铺列表
        $search_sql = "SELECT s.*,c.`channelName` FROM 3rd_shop s INNER JOIN 3rd_channel c ON s.channel=c.channelID $sqlStr ORDER BY s.shopID ";
        $shop_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
		return $shop_array ;
    }
    
    /**
     * 解释内容
     * @param $replyTradeIDArr
     */
    public function savereply($replyTradeIDArr){
        $msg = "";
        if(empty($replyTradeIDArr['trade_id'])){
            $msg .= '传参错误';
        }
        if(empty($replyTradeIDArr['reply'])){
            $msg .= "解释内容不能为空";
        }
        if($msg != ''){
            return array('code' => 400 , "message" => $msg);
        }
        
        $replyarr=array($replyTradeIDArr['reply'] , $replyTradeIDArr['trade_id']);
        $reply=$this->dbca->stmt_query('UPDATE 3rd_traderate SET reply=? WHERE trade_id = ?','ss',$replyarr);
       	return array('code' => 200 , "message" => "解释成功");
    }
    
    /**
     * 保存和更新评价
     *
     * @param unknown_type $shopID		店铺号
     * @param unknown_type $arg_array	参数信息
     * @return unknown
     */
	public function saveTraderate($shopID , $arg_array) {
		//参数检查
		if(!isset($shopID , $arg_array['created'] ,$arg_array['role'] , $arg_array['nick'] , $arg_array['oid'] , $arg_array['result'] , $arg_array['tid'])){
			return array('code' => 400 , 'message' => '参数错误');
		}
		
		$trade_id = number_format($arg_array['tid'],0,'','');									//交易号
		$order_id = number_format($arg_array['oid'],0,'','');									//子订单号
		$creator  = $arg_array['nick'];															//评价者
		$goodsName= isset($arg_array['item_title']) ? $arg_array['item_title'] : '';			//商品名称
		$salePrice= isset($arg_array['item_price']) ? $arg_array['item_price'] : '';			//商品价格
		$content  = isset($arg_array['content']) ? $arg_array['content'] : '';	 			 	//评论内容
		$reply	  = isset($arg_array['reply']) ? $arg_array['reply'] : '';						//解释内容
		$created  = $arg_array['created'];														//评价时间
		
		//评价等级
		$result = 0 ;
		if($arg_array['result'] == 'good')	{
			$result = 1 ;
		}else if($arg_array['result'] == 'neutral')	{
			$result = 2 ;
		}else if($arg_array['result'] == 'bad')	{	
			$result = 3 ;
		}	
		//评价角色
		$role = 1;
		if($arg_array['role'] == 'buyer'){
			$role = 1 ; 
		}elseif($arg_array['role'] == 'seller'){
			$role = 2 ;
		}
		
		//保存和更新评价
		$saveTraderate = new entity('3rd_traderate') ;
		$saveTraderate->shopID 	 = $shopID ;
		$saveTraderate->trade_id = $trade_id ;
		$saveTraderate->order_id = $order_id ;
		if($this->dbca->fetch($saveTraderate)){
			$saveTraderate->editor = $creator ;
		}else{ 
			$saveTraderate->creator = $creator;
		}	
		$saveTraderate->content 	= $content ;
		$saveTraderate->role 		= $role ;
		$saveTraderate->nick 		= $creator ;
		$saveTraderate->result	 	= $result;
		$saveTraderate->goodsName	= $goodsName;
		$saveTraderate->salePrice	= $salePrice;
		$saveTraderate->reply		= $reply;
		$saveTraderate->created		= $created;
		$saveTraderate->shopID		= $shopID;
		$this->dbca->save($saveTraderate , '3rd') ;
	}
	
    /**
     * 获取渠道
     */
     public function getChannel($channelID = null){
     	 if($channelID) 
         	$channel = $this->dbca->stmt_query('SELECT channelID,channelName FROM 3rd_channel WHERE channelID=?' , 'i' , $channelID);
     	 else 
     	 	$channel = $this->dbca->stmt_query('SELECT channelID,channelName FROM 3rd_channel');
     	 	
         return $channel;
     }
     
	 /**
	  * 取的商品类目 
	  *
	  * @return unknown
	  */
     public function getGoodsCategory($shopID , $pcid = 0){
         $goodsCategory = &$this->dbca->stmt_query('SELECT cid,name,is_parent,p_cid,sortOrder FROM 3rd_system_category WHERE shopID=? AND p_cid= ? ORDER BY sortOrder' , 'si' , $shopID , $pcid);
         return $goodsCategory;
     }

	
    /**
     * 保存商品授权类目
     *
     * @param unknown_type $cateArr 类目数组
     */
	public function save_category($shopID , $cateArr) {
		if($cateArr) {
			foreach ($cateArr as &$c_l){
				//参数不对则跳出
				if(!isset($c_l['cid'] , $c_l['is_parent'] , $c_l['name'] , $c_l['parent_cid'])){
					continue ;
				}
				
				//检查类目是否存在
				$issetCate = new entity('3rd_system_category') ;
				$issetCate->shopID = $shopID ;
				$issetCate->cid    = $c_l['cid'] ;
				if(!$this->dbca->fetch($issetCate)){
					$issetCate->creator   = 'system' ;
					$issetCate->name 	  = $c_l['name'] ;
					$issetCate->is_parent = $c_l['is_parent'] ;
					$issetCate->p_cid 	  = $c_l['parent_cid'];
					$issetCate->sortOrder = isset($c_l['sort_order']) ? $c_l['sort_order'] : '' ;
					$this->dbca->save($issetCate , '3rd') ;
				}
				
			}
		}
		
		return array('code' => 200 , 'message' =>'类目保存成功' ) ;
	}
	
	/**
	 * 保存商品标准类目描述模块化
	 *
	 * @param unknown_type $shopID			店铺号
	 * @param unknown_type $modules			模块名称
	 * @return unknown
	 */
	public function save_cateModules($shopID ,$cid , $modules) {
		if(!isset($shopID , $cid, $modules['module_id'] , $modules['module_name'])){
			return array('code'=>400,'message'=>'参数错误');
		}
		
		$moduleID 	= $modules['module_id'] ;		//模块号
		$moduleName = $modules['module_name'] ;		//模块名称
		$must		= isset($modules['required']) ? (int)$modules['required'] : 0 ;
		
		//保存商品类目模块
		$save_module = new entity('3rd_catemodules') ;
		$save_module->shopID   = $shopID ;
		$save_module->cid 	   = $cid ;
		$save_module->moduleID = $moduleID ;
		if(!$this->dbca->fetch($save_module)){
			$save_module->creator = 'system' ;
		}
		$save_module->moduleName = $moduleName ;
		$save_module->must 		 = $must ;
		$this->dbca->save($save_module , '3rd') ;
		
		return array('code' => 200 , 'message' =>'类目模块保存成功' ) ;
	}
	
	//宝贝列表
	public function goods_list(&$params){ 
		$sqlStr 	  = ' WHERE ';
        $params_type  = '';
        $params_array = array();
        
        //店铺
        if (isset($params['shopID']) && !empty($params['shopID'])) {
            $sqlStr 		.= ' gr.shopID = ?';
            $params_type 	.= 's';
            $params_array[]  = $params['shopID'];
        }else{
        	$sqlStr 		.= ' gr.shopID=1';
        }
        //宝贝编号
        if (isset($params['product_code']) && !empty($params['product_code'])) {
            $sqlStr .= ' AND gr.product_code = ?';
            $params_type .= 's';
            $params_array[] = $params['product_code'];
        }

        //宝贝名称
        if (isset($params['goodsName']) && !empty($params['goodsName'])) {
            $sqlStr .= ' AND gr.goodsName like ? ';
            $params_type .= 's';
            $params_array[] = '%'.$params['goodsName'].'%';
        }
        
		//是否已经上传
        if (isset($params['uFlg'])) {
            if($params['uFlg'] == 1)
	           $sqlStr .= ' AND gr.goodsCode IS NOT NULL ';
	           
	        elseif($params['uFlg'] == 2)
	           $sqlStr .= ' AND gr.goodsCode IS NULL ';
        }
        
		//最后修改时间
        if (isset($params['updateDate']) && !empty($params['updateDate'])) {
            $sqlStr .= ' AND gl.createTime >=? AND gl.createTime <=? ';
            $params_type .= 'ss';
            $params_array[] = $params['updateDate'] . ' 00:00:00' ;
            $params_array[] = $params['updateDate'] . ' 23:59:59' ;
        }
        
        //分页字符串
        $limitStr = '';

        if (isset($params['rp']) && $params['rp'] > 1) {

            //排序
            if (isset($params['sortname']) && !empty($params['sortname'])){
                $limitStr .= sprintf(' ORDER BY gl.%s %s', $params['sortname'], $params['sortorder']);
            }
            //分页
            if (!isset($params['page']) || !is_numeric($params['page']) || $params['page'] <= 0){
                $params['page'] = 1;
            }
            $limitStr .= sprintf(' LIMIT %d, %d', ($params['page'] - 1) * $params['rp'], $params['rp']);
            
            //统计数量
        	$count_sql = ' SELECT COUNT(DISTINCT(gr.product_code)) count FROM `3rd_goods_relation` gr LEFT JOIN `3rd_goods_log` gl ON gr.`product_code` = gl.`product_code` ' . $sqlStr ;
        	$listCount = $this->dbca->stmt_query($count_sql, $params_type, $params_array);
			$params['count'] = $listCount[0]->count ;
        } else {
            //排序
            if (isset($params['sortname']) && !empty($params['sortname'])){
                $limitStr .= sprintf(' ORDER BY gl.%s %s', $params['sortname'], $params['sortorder']);
            }
        }
        
        //查询宝贝例表
        $list_sql = ' SELECT DISTINCT gr.product_code,gr.goodsName ,gr.goodsCode,gr.shopID,sp.`title`,gr.modifiedTime FROM `3rd_goods_relation` gr
					  INNER JOIN `3rd_shop` sp ON sp.shopID=gr.`shopID` LEFT JOIN `3rd_goods_log` gl ON gr.`product_code` = gl.`product_code`  ' . $sqlStr . $limitStr;
        $listArr  = $this->dbca->stmt_query($list_sql , $params_type, $params_array);
		if(!$listArr){
			return null ;
		}
		if($listArr){
            foreach($listArr as $val){
                $result[] = array(
                    'product_code' => $val->product_code,
                    'shopID' 	   => $val->shopID,
                    'goodsName'    => $val->goodsName,
                    'title' 	   => $val->title,
                    'goodsCode'    => $val->goodsCode,
                    'modifiedTime' => $val->modifiedTime,
                );
            }
        }

        return $result;
	}
	
	/**
	 * 第三方平台生成商品生成操作类
	 * @package  	htdocs
	 * @subpackage  module/base
	 * @create by allen.qiang
	 * @version 	1.0
	 */
	public function goodsAdd($goodsInfo){
		if(!isset($goodsInfo['goodsName'], $goodsInfo['outer_id'] , $goodsInfo['marketPrice'] , $goodsInfo['salePrice'] , $goodsInfo['shopID'] , $goodsInfo['goodsCode'])){
			return array('code' => 400 , 'message' => '参数错误') ;
		}
		
		$goodsName 	 = $goodsInfo['goodsName'] ;									//商品名称
		$marketPrice = $goodsInfo['marketPrice'] ;									//商品市场价格
		$salePrice	 = $goodsInfo['salePrice'] ;									//商品销售价格
		$shopID		 = $goodsInfo['shopID'] ;										//店铺号
		$goodsCode	 = $goodsInfo['goodsCode'] ;									//平台代码 
		$pic_url	 = isset($goodsInfo['pic_url']) ?  $goodsInfo['pic_url'] : '';	//商品主图片
		$outer_id	 = $goodsInfo['outer_id'];										//商家编码
		$numbers	 = isset($goodsInfo['numbers']) ? $goodsInfo['numbers'] : 0;	//商品数量
		
		$commHandler = new commHandler($this->dbca);

		//检查商品是否存在
		$goods_sale_edit = new entity('goods_sale_edit');
		$goods_sale_edit->product_code = $outer_id;
		if(!$this->dbca->fetch($goods_sale_edit)){
			$mainPostID    = $commHandler->generate_seqno('seqno_post');			//一级商品号
			$two_goodsID   = $commHandler->generate_seqno('seqno_goods');			//二级商品号
			$two_postID    = $commHandler->generate_seqno('seqno_post');			//二级网购号
			$three_goodsID = $commHandler->generate_seqno('seqno_goods');			//三级商品号
			$three_postID  = $commHandler->generate_seqno('seqno_post');			//三级网购号
			
			//商品图片目录 
			$picDir = G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/goods/' . date('Ymd') . '/' . $two_goodsID.'/' ;
			if(!file_exists($picDir)){
				mkdir($picDir , 0777 , true);
			}

			$localPic = 'thumb_' . $two_goodsID .'.jpg';
			$wgetCmd  = sprintf('wget -t 10 -O "%s" "%s"' , $localPic , $pic_url);		//linux 命令
			chdir($picDir);																//改变工作目录
			system($wgetCmd);															//执行命令
			
			$mainPic = date('Ymd') . '/' . $two_goodsID . '/' . $localPic;				//图片路径

			//二级商品
			$goods_list_edit = new entity('goods_list_edit');
			$goods_list_edit->creator 		 = 'system';
			$goods_list_edit->mainPostID 	 = $mainPostID;
			$goods_list_edit->product_code 	 = $two_postID;
			$goods_list_edit->product_mainID = $mainPostID;
			$goods_list_edit->bigCategoryID  = 0;
			$goods_list_edit->midCategoryID  = 0;
			$goods_list_edit->midCategoryName= '';
			$goods_list_edit->useFlg 		 = 1;
			$goods_list_edit->postID 		 = $two_postID;
			$goods_list_edit->goodsID 		 = $two_goodsID;
			$goods_list_edit->goodsName 	 = $goodsName;
			$goods_list_edit->marketPrice 	 = $marketPrice;
			$goods_list_edit->salePrice 	 = $salePrice;
			$goods_list_edit->shopStr 		 = $shopID;
			$goods_list_edit->goodsMainPic 	 = $mainPic;
			
			//三级商品
			$goods_sale_edit->creator 		 = 'system';
			$goods_list_edit->product_code 	 = $outer_id;
			$goods_sale_edit->product_mainID = $mainPostID;
			$goods_sale_edit->mainPostID 	 = $mainPostID;
			$goods_sale_edit->twoPostID 	 = $two_postID;
			$goods_sale_edit->bigCategoryID  = 0;
			$goods_sale_edit->midCategoryID  = 0;
			$goods_sale_edit->midCategoryName= '';
			$goods_sale_edit->useFlg 		 = 1;
			$goods_sale_edit->postID 		 = $three_postID;
			$goods_sale_edit->goodsID 		 = $three_goodsID;
			$goods_sale_edit->goodsName 	 = $goodsName;
			$goods_sale_edit->marketPrice 	 = $marketPrice;
			$goods_sale_edit->salePrice 	 = $salePrice;
			$goods_sale_edit->shopStr 		 = $shopID;
			$goods_sale_edit->goodsMainPic 	 = $mainPic;
			
			$this->dbca->beginTransaction();
			try{	
				$this->dbca->save($goods_sale_edit);
				$this->dbca->save($goods_list_edit);
				$this->dbca->commit();
			}catch (Exception $e){
	            $this->dbca->rollBack();
	            error_log($e->getMessage());
	        }
		}else{
			$mainPic	= $goods_sale_edit->goodsMainPic ;
			$mainPostID = $goods_sale_edit->mainPostID ;
		}
		
        //生成xshop平台宝贝列表
        $platform_item = new entity('3rd_goods_relation');
        $platform_item->goodsCode = $goodsCode;
        $platform_item->shopID    = $shopID;
        if(!$this->dbca->fetch($platform_item)){
        	$platform_item->goodsMainPic = $mainPic ;
        	$platform_item->product_code = $mainPostID ;
        	$platform_item->outer_id 	 = $outer_id ;
        	$platform_item->goodsName 	 = $goodsName ;
        	$platform_item->goodsMainPic = $mainPic ;
        	$platform_item->marketPrice  = $marketPrice ;
        	$platform_item->salePrice  	 = $salePrice ;
        	$platform_item->numbers  	 = $numbers;
        	$platform_item->newFlg  	 = '';
        	$platform_item->onsale  	 = '';
        	$platform_item->feePayer  	 = '';
        	$platform_item->post_fee  	 = 0;
        	$platform_item->express_fee  = 0;
        	$platform_item->ems_fee  	 = 0;
        	$platform_item->sub_stock  	 = 0;
        	$this->dbca->save($platform_item);
        }

	}
	
	/**
	 * 保存商品详情模块化
	 *
	 * @param unknown_type $product_code		宝贝编码
	 * @param unknown_type $shopID				店铺号
	 * @param unknown_type $cid					子类目号
	 * @param unknown_type $moduleID			模块号
	 * @param unknown_type $content				模块内容
	 * @return unknown
	 */
	public function save_goodsModules($product_code , $shopID , $cid , $moduleID , $content) {
		if(!isset($product_code , $shopID, $cid , $moduleID , $content)){
			return array('code'=>400,'message'=>'参数错误');
		}
		
		//保存商品详情模块
		$save_module = new entity('3rd_goodsmodules') ;
		$save_module->product_code = $product_code ;
		$save_module->shopID 	   = $shopID ;
		$save_module->cid		   = $cid ;
		$save_module->moduleID	   = $moduleID ;
		if(!$this->dbca->fetch($save_module)){
			$save_module->creator = 'system' ;
		}
		$save_module->content = $content ;
		$this->dbca->save($save_module , '3rd') ;
		return array('code' => 200 , 'message' =>'商品详情模块保存成功' ) ;
	}
	
	/**
	 * 查询商标准类目描述模块化
	 *
	 * @param unknown_type $shopID			店铺号
	 * @param unknown_type $modules			模块名称
	 * @return unknown
	 */
	public function getCateModules($shopID , $cid) {
		$cateModule = $this->dbca->stmt_query('SELECT * FROM `3rd_catemodules` WHERE  shopID=? AND cid=? ORDER BY must DESC','si', $shopID , $cid);
		return $cateModule ;
	}
	
	/**
	 * 查询宝贝详情模块化
	 *
	 * @param unknown_type $product_code	宝贝编码
	 * @param unknown_type $shopID			店铺号
	 * @return unknown
	 */
	public function getGoodsModules($product_code , $shopID) {
		$goodsModules = $this->dbca->stmt_query('SELECT gm.content,cm.moduleID,cm.moduleName FROM 3rd_goodsmodules gm INNER JOIN 3rd_catemodules cm ON gm.shopID=cm.shopID AND gm.`cid`=cm.`cid` AND gm.`moduleID`=cm.`moduleID` WHERE gm.product_code=? AND gm.shopID=?','ss', $product_code , $shopID);
		return $goodsModules ;
	}
	
    /**
     * 保存商家产品类别
     * @param $channel
     * @param $cateArr
     */
    public function saveCustomCategory($shopID , $cateLine){
        //参数不对则跳出
        if(!isset($shopID , $cateLine['categoryID'] , $cateLine['categoryName'] , $cateLine['parent_id'] , $cateLine['sort_order'])){
            return array('code'=>400 , 'message'=>'参数错误');
        }

        //检查类目是否存在
        $issetCate = new entity('3rd_custom_category') ;
        $issetCate->categoryID = $cateLine['categoryID'];
        if(!$this->dbca->fetch($issetCate)){
            $issetCate->creator   	 = 'system' ;
            $issetCate->categoryID 	 = $cateLine['categoryID'] ;
            $issetCate->categoryName = $cateLine['categoryName'] ;
            $issetCate->parentID 	 = $cateLine['parent_id'];
            $issetCate->sortOrder 	 = $cateLine['sort_order'] ;
            $issetCate->is_parent	 = isset($cateLine['is_parent'])? $cateLine['is_parent'] : 0;
            $issetCate->shopID 		 = $shopID ;
            $this->dbca->save($issetCate , '3rd') ;
        }
        return array('code'=>200 , 'message'=>'商家自定义分类下载成功');
    }

    /**
     * 得到商家产品类别列表
     * @param $channelID
     * @return array|null
     */
    public function getCustomCategory($shopID){
		//参数判断
        if(!isset($shopID) || !is_numeric($shopID)){
            return array('code'=>400,'message'=>'参数错误');
        }

        $customCategory = $this->dbca->stmt_query('SELECT * FROM 3rd_custom_category WHERE shopID = ? and parentID = ?','si',array($shopID , 0));
        if($customCategory){
            foreach($customCategory  as $val){
                $result[] = array(
                    'categoryID'   => $val->categoryID,
                    'categoryName' => $val->categoryName,
                    'parentID' 	   => $val->parentID,
                    'sortOrder'	   => $val->sortOrder,
                    'shopID'       => $val->shopID,
                    'is_parent'	   => $val->is_parent
                );
            }

            return $result;
        }

    }

    //查询商品授权分类列表 
    public function sysCateList($params) {
    	global $G_PGLOB;

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();
		
		//店铺
		if (isset($params['shopID']) && !empty($params['shopID'])) {
			$sql .= ' AND tr.shopID = ?';
			$params_type .= 's';
			$params_array[] = $params['shopID'];
		}
		
		//类目号
		if (isset($params['cid']) && !empty($params['cid'])) {
			$sql .= ' AND tr.cid = ?';
			$params_type .= 'i';
			$params_array[] = $params['cid'];
		}

		//类目名称
		if (isset($params['name']) && !empty($params['name'])) {
			$sql .= ' AND tr.name LIKE ?';
			$params_type .= 's';
			$params_array[] = '%' . $params['name'] . '%';
		}
		
		//父类目号
		if(isset($params['fcid'])){
			$sql .= ' AND tr.p_cid = ?';
			$params_type .= 'i';
			$params_array[] = $params['fcid'] ;
		}
		
		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}
		
		//排序
		$limit = sprintf(' ORDER BY tr.%s %s', 'sortOrder', 'DESC');
		
		//查询分类信息
		$search_sql = 'SELECT tr.* , sp.`title` FROM 3rd_system_category tr LEFT JOIN `3rd_shop` sp ON sp.shopID=tr.shopID ' . $sql . $limit;
		$result_all = $this->dbca->stmt_query($search_sql , $params_type , $params_array);
		return $result_all ;
    }
   
	
    public function getBrand($shopID){
        if(!isset($shopID)){
            return array('code'=>400,'message'=>'参数错误');
        }
        
        $brand = $this->dbca->stmt_query('SELECT * FROM 3rd_brand WHERE shopID=?','s',$shopID);
        if($brand){
            foreach($brand  as $val){
                $result[] = array(
                    'pid' 		=>$val->pid,
                    'prop_name' => $val->prop_name,
                    'vid' 		=> $val->vid,
                    'brand_name'=> $val->brand_name,
                    'shopID'    => $val->shopID
                );
            }
            return $result;
        }

    }
    
    
    /**
     * 保存商品授权品牌
     *
     * @param unknown_type $brandArr 品牌数组
     */
	public function save_brand($shopID , $brandArr){
		if($brandArr) {
			foreach ($brandArr as &$b_l){
				//参数不对则跳出
				if(!isset($b_l['name'] , $b_l['pid'] , $b_l['prop_name'] , $b_l['vid'])){
					continue ;
				}
				//检查品牌是否已经存在 
				$issetBrand = new entity('3rd_brand') ;
				$issetBrand->shopID 	= $shopID ;
				$issetBrand->brand_name = $b_l['name'] ;
				if(!$this->dbca->fetch($issetBrand)){
					$issetBrand->pid = $b_l['pid'] ;
					$issetBrand->vid = $b_l['vid'] ;
					$issetBrand->prop_name = $b_l['prop_name'] ;
					$this->dbca->save($issetBrand,'3rd') ;
				}
			}
		}
		
		return array('code' => 200 , 'message' =>'品牌保存成功' ) ;
	}
	
	/**
	 * 保存宝贝属性和属性值 
	 *
	 * @param unknown_type $shopID  
	 * @param unknown_type $props
	 */
	public function saveProps($shopID , $cid , $props) {
		if(!isset($shopID , $cid , $props['pid'] , $props['name'])){
			return array('code' => 400 , 'message' => '参数错误');
		}
	
		//参数判断	
		$propsValus = isset($props['prop_values']['prop_value']) ? $props['prop_values']['prop_value'] : null ;
		$this->dbca->beginTransaction() ;
		try{
			//如果没有类型则默认为输入型
			if($props['multi'] == '' && $props['is_enum_prop'] == ''){
				$props['is_input_prop'] = 1;
			}
			
			//保存宝贝属性
			$saveProp = new entity('3rd_props') ;
			$saveProp->shopID  = $shopID ;
			$saveProp->cid	   = $cid ;
			$saveProp->pid	   = $props['pid'] ;
			$saveProp->pname   = $props['name'] ;
			if(!$this->dbca->fetch($saveProp)){
				$saveProp->p_pid   = isset($props['parent_pid']) ? $props['parent_pid'] : 0;
				$saveProp->p_vid   = isset($props['parent_vid']) ? $props['parent_vid'] : 0;
				$saveProp->must    = intval($props['must']) ;
				$saveProp->multi   = intval($props['multi']) ;
				$saveProp->is_key  = intval($props['is_key_prop']) ;
				$saveProp->is_sale = intval($props['is_sale_prop']) ;
				$saveProp->is_input= intval($props['is_input_prop']) ;
				$saveProp->is_alias= intval($props['is_allow_alias']) ;
				$saveProp->is_enum = intval($props['is_enum_prop']) ;
				$saveProp->is_color= intval($props['is_color_prop']) ;
				$saveProp->is_item = intval($props['is_item_prop']) ;
				$saveProp->creator = 'system' ;
				$saveProp->sortOrder = isset($props['sortOrder']) ? $props['sortOrder'] : 0;
				$this->dbca->save($saveProp , '3rd') ;
			}
			
			//保存宝贝属性值 
			if($propsValus){
				foreach($propsValus as &$p_v) {
					$savePropValue = new entity('3rd_prop_value') ;
					$savePropValue->shopID  = $shopID ;
					$savePropValue->cid 	= $cid;
					$savePropValue->pid 	= $props['pid'] ;
					$savePropValue->vid 	= $p_v['vid'] ;
					$savePropValue->vname 	= $p_v['name'] ;
					if(!$this->dbca->fetch($savePropValue)){
						$savePropValue->creator   = 'system' ;
						$savePropValue->vname 	  = $p_v['name'] ;
						$savePropValue->alias 	  = $p_v['name'] ;
						$savePropValue->is_parent = isset($p_v['is_parent']) ? $p_v['is_parent'] : 0 ;
						$this->dbca->save($savePropValue , '3rd') ;
					}
				}
			}
			
			$this->dbca->commit() ;
		}catch(Exception $e) {
			$this->dbca->rollBack() ;
			error_log($e->getMessage()) ;
			return array('code' => 500 , 'message' => '保存属性失败');
		}
	}
	
	/**
	 * 格式化天猫交易接口
	 *
	 * @param unknown_type $tradeInfo
	 */
	public function TBtradeFormat($shopID , $shopCode , $tradeInfo) {
		$billArray = array() ;
		$tid = number_format($tradeInfo['tid'],0,'','') ;
		
		//==========================================天猫会员注册==================================
		$buyer_nick = $tradeInfo['buyer_nick'] ;
		$custID		= md5($buyer_nick) . '@taobao.com' ;
		
		//交易促销信息
		$promotion_details = isset($tradeInfo['promotion_details']['promotion_detail']) ? $tradeInfo['promotion_details']['promotion_detail'] : null ;
		
		//总的优惠金额
		$subtract_money =  0 ;				
		if($promotion_details){
			foreach($promotion_details as &$p_l) {
				$subtract_money += $p_l['discount_fee'] ;
			}
		}
		
		$custHandler = new customerHandler($this->dbca) ;
		
		//检查会员是否已经存在 
		$reg_array = array('custID' => $custID) ;
		$custInfo  = $custHandler->getCustomerInfo($reg_array) ;
		if(!$custInfo){
			//注册成新会员
			$regPwd		= rand(1111111, 9999999) ;
			$reg_array	= array( 'regName'  => $custID ,
								 'regPwd'   => $regPwd ,
								 'regPwd2'  => $regPwd ,
								 'custType' => 1) ;
								 
			$custInfo = $custHandler->addCustomer($reg_array) ;
			if($custInfo['code'] == 200){
				$pcustID = $custInfo['data']['pcustID'] ;
				//保存第三方会员和官网会员对应关系 
				$this->save_3rdCust_rel($custID , $pcustID , $buyer_nick , $shopID) ;
			}else{
				return array ('code' => $custInfo['code'] , 'message' => $custInfo['message']) ;
			}
		}else{
			$pcustID = $custInfo[0]['pcustID'] ;
		}
		//========================================天猫会收货的地址处理===================================
		
		$deliver_array = array( 'pcustID' 	 => $pcustID,
								'creator' 	 => 'system' ,
								'custName'	 => $tradeInfo['receiver_name'],
								'provinceid' => 0,
								'province' 	 => $tradeInfo['receiver_state'] ,
								'cityid' 	 => 0,
								'city'		 => $tradeInfo['receiver_city'],
								'countyid' 	 => 0,
								'county' 	 => isset($tradeInfo['receiver_district']) ? $tradeInfo['receiver_district']: '' ,
								'postalCode' => isset($tradeInfo['receiver_zip'])?$tradeInfo['receiver_zip']:'' ,
								'address' 	 => $tradeInfo['receiver_address'],
								'mobile' 	 => isset($tradeInfo['receiver_mobile']) ? $tradeInfo['receiver_mobile'] : '',
								'phone' 	 => isset($tradeInfo['receiver_phone'])? $tradeInfo['receiver_phone'] : '' ,) ;
								
		$this->receiverAddress($deliver_array) ;
		
		//==============================================生成本地收货地址ID================================
		
		$customerHandler = new customerHandler($this->dbca);
		$get_custdeliver = new entity('cust_deliver') ;
		$get_custdeliver->pcustID 	 = $deliver_array ['pcustID'] ;
		$get_custdeliver->provinceid = $deliver_array ['provinceid'] ;
		$get_custdeliver->cityid     = $deliver_array ['cityid'] ;
		$get_custdeliver->countyid   = $deliver_array ['countyid'] ;
		if($this->dbca->fetch ($get_custdeliver)){
			$deliver_array ['deliverID'] = $get_custdeliver->deliverID ;
		}
		$deliverMsg = $customerHandler->editCustDeliver($deliver_array);
		if($deliverMsg['code'] != 200) {
			//如果找不到配送信息则直接默认配送方式 
			$deliverID = 4 ;	
		}else{
			$deliverID = $deliverMsg['data']['deliverID'] ;
		}
		
		//==============================================组成订单数组==============================
		
		$billArray['pcustID'] = $pcustID ;	
		$billArray['custID']  = $buyer_nick ;				
		$billArray['master']  = array(
				 'deliverid' 		 => $deliverID,
				 'extCustID' 		 => $buyer_nick,
				 'deliver_province'  => $deliver_array ['province'] ,
				 'deliver_city'		 => $deliver_array ['city'] ,
				 'deliver_county'	 => $deliver_array ['county'] ,
				 'deliver_address'	 => $deliver_array ['address'] ,
				 'deliver_postalCode'=> $deliver_array ['postalCode'] ,
				 'deliver_name'		 => $deliver_array ['custName'] ,
				 'deliver_mobile'	 => $deliver_array ['mobile'] ,
				 'deliver_phone'	 => $deliver_array ['phone'] ,
				 'countyid'			 => $deliver_array ['countyid'] ,
				 'cityid'			 => $deliver_array ['cityid'] ,
				 'provinceid'		 => $deliver_array ['provinceid'] ,
				 'billType'			 => 2 ,
				 'shopCode'			 => $shopCode ,
				 'remark'				  => isset($tradeInfo['buyer_message']) ? $tradeInfo['buyer_message'] : '',
				 'deliver_send_time_id'   => 30 ,
				 'deliver_send_time_name' => '工作日、双休日与假日均可送货' ,
				 'invoice' 				=> isset($tradeInfo['invoice_name']) ? 1 : 0,
				 'invoice_title_type'	=> 1,
				 'invoice_title'		=> isset($tradeInfo['invoice_name'])? $tradeInfo['invoice_name'] : '',
				 'invoice_content'		=> '',
				 'bill_subtract_money'	=> $subtract_money
		) ;
									
		$billArray['bill_no'] 	  = '';																			//订单号
		$billArray['buyer_nick']  = $buyer_nick;																//购买者
		$billArray['bill_status'] = 0;																			//订单状态
		$billArray['goods']['general'] =  array();																//订单商品
		$billArray['tid'] 	  	  = $tid;																		//淘宝交易号
		$billArray['pay_time'] 	  = isset($tradeInfo['pay_time']) ? $tradeInfo['pay_time'] : null;				//支付时间
		$billArray['pay_code']    = isset($tradeInfo['alipay_no'])?$tradeInfo['alipay_no']: '' ;				//支付码
		$billArray['totalMoney']  = $tradeInfo['total_fee'] ;													//订单商品金额
		$billArray['totalPaid']   = $tradeInfo['payment'] - $tradeInfo['post_fee'];								//订单实付金额
		$billArray['discount_fee']= $tradeInfo['discount_fee'] ;												//优惠的金额
		$billArray['point_fee']   = $tradeInfo['real_point_fee'] ;												//实际使用积分
		$billArray['post_fee']    = $tradeInfo['post_fee'] ;													//订单邮费
		$billArray['vender_remark'] = isset($tradeInfo['seller_memo'])?$tradeInfo['seller_memo'] : null ;		//内部留言
		
		//==============================================配送方式================================

		if(!isset($billArray['master']['sendTypeID'])){
			$billArray['master']['sendTypeID'] 	  	 = DELIVERID ;		
			$billArray['master']['send_region_id'] 	 = 10 ;	
			$billArray['master']['send_region_name'] = '全国' ;
			$billArray['master']['sendTypeName'] 	 = '快递';
		}

		//==============================================支付方式保存================================
		if($tradeInfo['type'] == 'cod'){
			$billArray['master']['pay_type'] 	= 1;
            $billArray['master']['payTypeID']   = 1;
            $billArray['master']['payTypeName'] = '货到付款';
            $billArray['master']['pay_status']	= 0;
		}else{
			$billArray['master']['pay_type'] 	= 2;
            $billArray['master']['payTypeID']   = TBPAY;
            $billArray['master']['payTypeName'] = '支付宝';
            $billArray['master']['pay_status']	= 1;
		}
		//==============================================订单商品处理================================
		$goodsArray   = isset($tradeInfo['orders']['order'])?  $tradeInfo['orders']['order'] : '';
		$goodsHandler = new goodsHandler();
		
		if($goodsArray) {
			foreach($goodsArray as &$g_l){
				//得到第三方商品编码
				$goodsCode = isset($g_l['outer_sku_id'])? $g_l['outer_sku_id'] : $g_l['outer_iid'] ;
				$goodsInfo = $this->get_trades_goods('8000500005026') ;
				if($goodsInfo){
					$goodsInfo = $goodsInfo[0] ;
					//商品单价
					$price = round($g_l['total_fee'] / $g_l['num'] , 2) ;				
					//将商品加入订单商品数组中	 
					$billArray['goods']['general'][] = array('goodsID' 		=> $goodsInfo->goodsID ,
															'postID'  		=> $goodsInfo->postID ,
															'goodsName'  	=> $g_l['title'],
															'spec'  	 	=> '' ,
															'goods_amount'  => $g_l['num'] ,
															'salePrice'  	=> $g_l['price'] ,
															'marketPrice' 	=> $g_l['price'],
															'price'  		=> $price ,
															'addPoints'  	=> 0 ,
															'salePoints'  	=> 0 ,
															'goodsWeight'  	=> 0 ,
															'goods_from'  	=> 1 ,
															'goods_groupID' => 0,
															'goods_status'  => 1,
															'img_link'  	=> $goodsHandler->setImgLink($goodsInfo->goodsMainPic),
															'link'  		=> $goodsHandler->setLink($goodsInfo->uid),
															'wap_link'  	=> $goodsHandler->setWapLink($goodsInfo->uid),
															'bigCategoryID' => $goodsInfo->bigCategoryID,
															'midCategoryID' => $goodsInfo->midCategoryID,
															'smallCategoryID' => $goodsInfo->smallCategoryID,
															'product_code' 	=> $goodsCode,
															'twoPostID' 	=> $goodsInfo->twoPostID,
															'promotion' 	=> array(),
															) ;
				}else{
					return array('code' => 400 ,'message' => sprintf('交易号「%s」的商品编码「%s」商品不存在' , $tid , $goodsCode)) ;
				}
			}
		}

		return array('code' => 200 ,'message' => $billArray) ;
	}
	
	//格式化京东交易接口
	public function JDtradeFormat($shopID , $shopCode , $tradeInfo){
		//参数判断
		if(!isset($tradeInfo['order_id'] , $tradeInfo['order_total_price'] , $tradeInfo['order_payment'] , $tradeInfo['item_info_list'])){
			return array('code' => 400 ,'message' => '交易数据格式错误') ;
		}
		$modified 	= isset($tradeInfo['modified']) ?  $tradeInfo['modified'] : '' ;							//交易最后修改时间
		$order_id 	= isset($tradeInfo['order_id']) ?  $tradeInfo['order_id'] : '' ;							//交易号
		$pay_type   = isset($tradeInfo['pay_type']) ?  $tradeInfo['pay_type'] : '' ;							//支付方式
		$totalPrice = isset($tradeInfo['order_total_price']) ?  $tradeInfo['order_total_price'] : 0 ;			//总金额
		$payment 	= isset($tradeInfo['order_payment']) ?  $tradeInfo['order_payment'] : 0 ;					//用户应付金额
		$sellerPrice   = isset($tradeInfo['order_seller_price']) ?  $tradeInfo['order_seller_price'] : 0 ;		//订单货款金额（订单总金额-商家优惠金额）
		$freightPrice  = isset($tradeInfo['freight_price']) ?  $tradeInfo['freight_price'] : 0 ;				//交易运费
		$invoice_info  = isset($tradeInfo['invoice_info']) ?  $tradeInfo['invoice_info'] : '' ;	 				//发票信息
		$order_remark  = isset($tradeInfo['order_remark']) ?  $tradeInfo['order_remark'] : '' ;					//买家下单时订单备注
		$order_time	   = isset($tradeInfo['order_start_time']) ?  $tradeInfo['order_start_time'] : '' ;			//下单时间
		$deliver_info  = isset($tradeInfo['consignee_info']) ?  $tradeInfo['consignee_info'] : array() ; 		//收货人基本信息
		$item_list	   = isset($tradeInfo['item_info_list']) ?  $tradeInfo['item_info_list'] : array() ;		//商品列表
		$coupon_list   = isset($tradeInfo['coupon_detail_list']) ?  $tradeInfo['coupon_detail_list'] : array() ;//优惠列表信息
		$vender_remark = isset($tradeInfo['vender_remark']) ?  $tradeInfo['vender_remark'] :'' ;				//商家订单备注（不大于500字符）
		$payment_time  = isset($tradeInfo['payment_confirm_time']) ? $tradeInfo['payment_confirm_time'] :'' ; 	//支付时间
		$parent_order  = isset($tradeInfo['parent_order_id']) ? $tradeInfo['parent_order_id'] :'' ; 			//父交易号
		$balance_used  = isset($tradeInfo['balance_used']) ? $tradeInfo['balance_used'] : 0 ; 					//余额支付金额
		$buyer_nick	   = isset($tradeInfo['pin']) ? $tradeInfo['pin'] : 'fk' . time(); 							//即买家的账号信息
		
		$payment = $payment - $freightPrice ;
		//============================================会员信息处理===========================================
		
		$custID = md5($buyer_nick) . '@jd.com' ;				//会员号

		//检查会员是否存在
		$custHandler = new customerHandler($this->dbca) ;
		$reg_array 	 = array('custID' => $custID) ;
		$custInfo  	 = $custHandler->getCustomerInfo($reg_array) ;
		if(!$custInfo){
			//注册成新会员 , 随机密码
			$passwd	   = rand(1111111, 9999999) ;					
			$reg_array = array( 'regName'  => $custID ,
								 'regPwd'   => $passwd ,
								 'regPwd2'  => $passwd ,
								 'custType' => 1) ;
			$custInfo = $custHandler->addCustomer($reg_array) ;
			if($custInfo['code'] == 200){
				$pcustID = $custInfo['data']['pcustID'] ;
				//保存第三方会员和官网对应关系 
				$this->save_3rdCust_rel($custID , $pcustID , $buyer_nick , $shopID) ;
			}else{
				return array ('code' => $custInfo['code'] , 'message' => $custInfo['message']) ;
			}
		}else{
			$pcustID = $custInfo[0]['pcustID'] ;
		}	
		//=====================================配送信息处理======================================
		$receiver_name 	  = $deliver_info['fullname'] ;													//收货人
		$receiver_mobile  = isset($deliver_info['mobile']) ? $deliver_info['mobile'] : '' ;				//手机号
		$receiver_phone   = isset($deliver_info['telephone']) ? $deliver_info['telephone'] : '' ;		//电话号
		$deliver_province = isset($deliver_info['province']) ? $deliver_info['province'] : '' ;			//省
		$receiver_city	  = isset($deliver_info['city']) ? $deliver_info['city'] : '' ;					//市
		$receiver_county  = isset($deliver_info['county']) ? $deliver_info['county'] : '' ;				//区
		$deliver_address  = isset($deliver_info['full_address']) ? $deliver_info['full_address'] : '' ;	//地址
		
		$deliver_array = array( 
				'pcustID' 	 => $pcustID ,
				'creator' 	 => 'system' ,
				'custName'	 => $receiver_name,
				'provinceid' => 0 ,
				'province' 	 => $deliver_province ,
				'cityid' 	 => 0 ,
				'city'		 => $receiver_city,
				'countyid' 	 => 0,
				'county' 	 => $receiver_county ,
				'postalCode' => '' ,
				'address' 	 => $deliver_address ,
				'mobile' 	 => $receiver_mobile ,
				'phone' 	 => $receiver_mobile=='' ? $receiver_phone : ''
		) ;	
		//地址转化
		$this->receiverAddress($deliver_array) ;
		
		//==============================================生成配送方式号================================
		
		//如果有省，市，区则直接修改地址
		$get_custdeliver = new entity('cust_deliver') ;
		$get_custdeliver->pcustID 	 = $deliver_array ['pcustID'] ;
		$get_custdeliver->provinceid = $deliver_array ['provinceid'] ;
		$get_custdeliver->cityid     = $deliver_array ['cityid'] ;
		$get_custdeliver->countyid   = $deliver_array ['countyid'] ;
		if($this->dbca->fetch ($get_custdeliver)){
			$deliver_array ['deliverID'] = $get_custdeliver->deliverID ;
		}
		
		//修改会员的配送地址	
		$deliverMsg = $custHandler->editCustDeliver($deliver_array);
		if($deliverMsg['code'] != 200) {
			$deliverID = 4 ;
		}else{
			$deliverID = $deliverMsg['data']['deliverID'] ;
		}
		//==============================================订单优惠处理=============================
		
		$card_money     = 0 ;		//礼品卡金额
		$coupon_money   = 0 ;		//优惠券金额
		$subtract_money = 0 ;		//订单立减
		if($coupon_list) {
			foreach($coupon_list as &$c_l) {
				if(in_array($c_l['coupon_type'] , array('20-套装优惠', '28-闪团优惠' , '29-团购优惠' , '30-单品促销优惠' , '34-手机红包' , '35-满返满送(返现)' , '39-京豆优惠' , '100-店铺优惠')))
					$subtract_money += $c_l['coupon_price'];
				else if($c_l['coupon_type'] == '41-京东券优惠')
					$coupon_money += $c_l['coupon_price'];
				else if($c_l['coupon_type'] == '52-礼品卡优惠')	
					$card_money += $c_l['coupon_price'];	
			}
		}
		
		//=============================================发票处理====================================
		
		$invoice 	  		= 0 ;						//是否存在发票
		$invoice_type	    = 1 ;						//普通发票类型
		$invoice_title_type	= 1 ;						//发票抬头类型
		$invoice_title		= '' ;						//发票抬头
		
		if($invoice_info != ''){
			$invoice = 1 ;
			$invoiceArr = explode(';' , $invoice_info) ;
			if($invoiceArr){
				foreach($invoiceArr as &$i_l){
					if(empty($i_l)){
						continue ;
					}
					$i_arr = explode(':' , $i_l) ;
					if(isset($i_arr[0]) && isset($i_arr[1])){
						//发票类型处理
						if($i_arr[0] == '发票类型'){
							if($i_arr[1] == '增值税发票'){
								$invoice_type = 1 ;
							}
						}
						
						//发票抬头类型
						if($i_arr[0] == '发票抬头'){
							if($i_arr[1] == '个人'){
								$invoice_title_type = 1 ;
							}elseif($i_arr[1] == '单位'){
								$invoice_title_type = 2 ;	
							}
						}
						
						//发票内容
						if($i_arr[0] == '发票内容'){
							$invoice_title = $i_arr[1] ;
						}
						
					}
				}
			}
		}
		
		//==============================================组成订单数组==============================
		   				
		$billArray = array() ;
		$billArray['pcustID'] = $pcustID ;	
		$billArray['custID']  = $custID ;	
		$billArray['master']  = array(
				 'deliverid' 			=> $deliverID,
				 'bill_subtract_money'  => $subtract_money ,
				 'bill_coupon_money'  	=> $coupon_money ,
				 'bill_card_money'  	=> $card_money ,
				 'deliver_province' 	=> $deliver_array ['province'] ,
				 'deliver_city'			=> $deliver_array ['city'] ,
				 'deliver_county'		=> $deliver_array ['county'] ,
				 'deliver_address'		=> $deliver_array ['address'] ,
				 'deliver_postalCode'	=> $deliver_array ['postalCode'],
				 'deliver_name'			=> $deliver_array ['custName'] ,
				 'deliver_mobile'		=> $deliver_array ['mobile'] ,
				 'deliver_phone'		=> $deliver_array ['phone'] ,
				 'countyid'				=> $deliver_array ['countyid'] ,
				 'cityid'				=> $deliver_array ['cityid'] ,
				 'provinceid'			=> $deliver_array ['provinceid'] ,
				 'billType'				=> 3 ,
				 'extCustID'			=> $buyer_nick ,
				 'remark'				=> $order_remark,
				 'shopCode'				=> $shopCode ,
				 'deliver_send_time_id'   => 30 ,
				 'deliver_send_time_name' => '工作日、双休日与假日均可送货' ,
				 'invoice' 				=> $invoice,
				 'invoice_title_type'	=> $invoice_title_type,
				 'invoice_title'		=> $invoice_title,
				 'invoice_content' 		=> $invoice_title,
		) ;
									
		$billArray['bill_no'] 	  		= '';																			//订单号
		$billArray['bill_status'] 		= 0;																			//订单状态
		$billArray['goods']['general']  = array();																		//订单商品
		$billArray['tid'] 	  	  		= $order_id;																	//交易号
		$billArray['pay_time'] 	  		= $payment_time;																//支付时间
		$billArray['pay_code']   		= '';																			//订单支付码	
		$billArray['totalMoney'] 		= $totalPrice ;																	//订单商品金额
		$billArray['totalPaid']   		= $payment;																		//订单实付金额
		$billArray['post_fee']    		= $freightPrice;																//订单邮费
		$billArray['vender_remark']   	= $vender_remark;																//商家留言
		
		//订单商品处理
		if($item_list) {
			$goodsHandler = new goodsHandler();
			foreach($item_list as &$g_l){
				//得到第三方商品编码
				$goodsCode = isset($g_l['outer_sku_id'])? $g_l['outer_sku_id'] : '' ;				
				$goodsInfo = $this->get_trades_goods('8000500005026') ;
				
				//订单商品处理
				if($goodsInfo){
					$goodsInfo = $goodsInfo[0] ;
					$billArray['goods']['general'][] = array('goodsID' 		=> $goodsInfo->goodsID ,
															'postID'  		=> $goodsInfo->postID ,
															'goodsName'  	=> $g_l['sku_name'] ,
															'spec'  	 	=> '' ,
															'goods_amount'  => $g_l['item_total'] ,
															'salePrice'  	=> $g_l['jd_price'] ,
															'price'  		=> $g_l['jd_price'],
															'marketPrice' 	=> $g_l['jd_price'],
															'addPoints'  	=> 0 ,
															'salePoints'  	=> 0 ,
															'goodsWeight'  	=> 0 ,
															'goods_from'  	=> 1 ,
															'goods_groupID' => 0 ,
															'goods_status'  => 1 ,
															'img_link'  	=> $goodsHandler->setImgLink($goodsInfo->goodsMainPic),
															'link'  		=> $goodsHandler->setLink($goodsInfo->uid),
															'wap_link'  	=> $goodsHandler->setWapLink($goodsInfo->uid),
															'bigCategoryID' => $goodsInfo->bigCategoryID,
															'midCategoryID' => $goodsInfo->midCategoryID,
															'smallCategoryID' => $goodsInfo->smallCategoryID,
															'product_code' 	=> $goodsCode,
															'twoPostID' 	=> $goodsInfo->twoPostID,
															
															'promotion' 	=> array(),
															) ;
				}else {
					return array('code' => 400 ,'message' => sprintf('交易号「%s」的商品编码「%s」商品不存在' , $order_id , $goodsCode)) ;
				}
			}
		}

		//=============================================配送方式=================================
		//如果配送方式找不到则默认一个配送方式
		if(!isset($billArray['master']['sendTypeID'])){
			$billArray['master']['sendTypeID'] 	  	 = DELIVERID ;		
			$billArray['master']['send_region_id'] 	 = 10 ;	
			$billArray['master']['send_region_name'] = '全国' ;
			$billArray['master']['sendTypeName'] 	 = '快递';
		}
		//==============================================支付方式保存================================
		
		if($pay_type == '1-货到付款') {
			//货到付款标志
			$billArray['master']['pay_type'] 	= 1;
            $billArray['master']['payTypeID']   = 1;
            $billArray['master']['payTypeName'] = '货到付款';
            $billArray['master']['pay_status']	= 0;
		}else{
			$billArray['master']['pay_type'] 	= 2;
            $billArray['master']['payTypeID']   = EXTPAY;
            $billArray['master']['payTypeName'] = '第三方平台支付';
            $billArray['master']['pay_status']	= 1;
		}	

		return array('code' => 200 ,'message' => $billArray) ;
		
	}
	
	//格式化一号店交易接口
	public function YHDtradeFormat($shopID , $shopCode , $tradeInfo){
		
		//参数判断
		if(!isset($tradeInfo['orderDetail']['orderCode'] , $tradeInfo['orderDetail']['orderAmount'] , $tradeInfo['orderDetail']['goodReceiverName'] , $tradeInfo['orderItemList']['orderItem'])){
			return array('code' => 400 ,'message' => '交易数据格式错误') ;
		}
		$modified 	= isset($tradeInfo['orderDetail']['updateTime']) ?  $tradeInfo['orderDetail']['updateTime'] : '' ;								//交易最后修改时间
		$order_id 	= isset($tradeInfo['orderDetail']['orderCode']) ?  $tradeInfo['orderDetail']['orderCode'] : '' ;								//交易号
		$pay_type   = isset($tradeInfo['orderDetail']['payServiceType']) ?  $tradeInfo['orderDetail']['payServiceType'] : '' ;						//支付方式
		$totalPrice = isset($tradeInfo['orderDetail']['productAmount']) ?  $tradeInfo['orderDetail']['productAmount'] : 0 ;							//总金额
		$payment 	= isset($tradeInfo['orderDetail']['orderAmount']) ?  $tradeInfo['orderDetail']['orderAmount'] : 0 ;								//用户应付金额
		$freightPrice  = isset($tradeInfo['orderDetail']['orderDeliveryFee']) ?  $tradeInfo['orderDetail']['orderDeliveryFee'] : 0 ;				//交易运费
		$invoice  	   = isset($tradeInfo['orderDetail']['orderNeedInvoice']) ?  $tradeInfo['orderDetail']['orderNeedInvoice'] : 0 ;	 			//发票需要情况: 0 不需要，1旧版普通，2新版普通，3增值税发票
		$order_remark  = isset($tradeInfo['orderDetail']['deliveryRemark']) ?  $tradeInfo['orderDetail']['deliveryRemark'] : '' ;					//买家下单时订单备注
		$order_time	   = isset($tradeInfo['orderDetail']['orderCreateTime']) ?  $tradeInfo['orderDetail']['orderCreateTime'] : '' ;					//下单时间
		$item_list	   = isset($tradeInfo['orderItemList']['orderItem']) ?  $tradeInfo['orderItemList']['orderItem'] : array() ;					//商品列表
		$vender_remark = isset($tradeInfo['orderDetail']['merchantRemark']) ?  $tradeInfo['orderDetail']['merchantRemark'] :'' ;					//商家订单备注	
		$payment_time  = isset($tradeInfo['orderDetail']['orderPaymentConfirmDate']) ? $tradeInfo['orderDetail']['orderPaymentConfirmDate'] :'' ; 	//支付时间
		$buyer_nick	   = isset($tradeInfo['orderDetail']['endUserId']) ? $tradeInfo['orderDetail']['endUserId'] : 'fk' . time(); 					//用户ID
		$invoiceArray  = isset($tradeInfo['invoiceInfo']) ? $tradeInfo['invoiceInfo'] : array(); 													//发票数组
		$payment = $payment - $freightPrice ;
		//============================================会员信息处理===========================================
		
		
		//检查会员是否存在
		$custHandler = new customerHandler($this->dbca) ;
		$custID 	 = $buyer_nick . '@yhd.com' ;						//会员名称
		$reg_array 	 = array('custID' => $custID) ;
		$custInfo  	 = $custHandler->getCustomerInfo($reg_array) ;
		if(!$custInfo){
			//注册成新会员 , 随机密码
			$passwd 	= rand(1111111, 9999999) ;					
			$reg_array	= array( 'regName'  => $custID ,
								 'regPwd'   => $passwd ,
								 'regPwd2'  => $passwd ,
								 'custType' => 1) ;
								 			 
			$custInfo 	 = $custHandler->addCustomer($reg_array) ;
			if($custInfo['code'] == 200){
				$pcustID = $custInfo['data']['pcustID'] ;
				
				//保存第三方会员和官网对应关系 
				$this->save_3rdCust_rel($custID , $pcustID , $buyer_nick , $shopID) ;
			}else{
				return array ('code' => $custInfo['code'] , 'message' => $custInfo['message']) ;
			}
		}else{
			$pcustID = $custInfo[0]['pcustID'] ;
		}
		//=====================================配送信息处理======================================
		
		$receiver_name 	  = $tradeInfo['orderDetail']['goodReceiverName']; 																			//收货人
		$receiver_mobile  = isset($tradeInfo['orderDetail']['goodReceiverMoblie']) ? $tradeInfo['orderDetail']['goodReceiverMoblie'] : ''	;		//手机号
		$receiver_phone   = isset($tradeInfo['orderDetail']['goodReceiverPhone']) ? $tradeInfo['orderDetail']['goodReceiverPhone'] : '' ;			//电话号
		$deliver_province = isset($tradeInfo['orderDetail']['goodReceiverProvince']) ? $tradeInfo['orderDetail']['goodReceiverProvince'] : '' ;		//省
		$receiver_city	  = isset($tradeInfo['orderDetail']['goodReceiverCity']) ? $tradeInfo['orderDetail']['goodReceiverCity'] : '' ;				//市
		$receiver_county  = isset($tradeInfo['orderDetail']['goodReceiverCounty']) ? $tradeInfo['orderDetail']['goodReceiverCounty'] : '' ;			//区
		$goodReceiverArea = isset($tradeInfo['orderDetail']['goodReceiverArea']) ? $tradeInfo['orderDetail']['goodReceiverArea'] : '' ;				//收货人街道地址
		$deliver_address  = isset($tradeInfo['orderDetail']['goodReceiverAddress']) ? $tradeInfo['orderDetail']['goodReceiverAddress'] : '' ;		//地址
		$deliver_address  = $goodReceiverArea . $deliver_address ;																					//将街道地址合并到地址里
		$postalCode		  = isset($tradeInfo['orderDetail']['goodReceiverPostCode']) ? $tradeInfo['orderDetail']['goodReceiverPostCode'] : '' ;		//收货人邮编
		$coupon_money     = isset($tradeInfo['orderDetail']['orderCouponDiscount']) ? $tradeInfo['orderDetail']['orderCouponDiscount'] : 0 ;		//商家抵用券支付金额
		$coupon_money	  += isset($tradeInfo['orderDetail']['orderPlatformDiscount']) ? $tradeInfo['orderDetail']['orderPlatformDiscount'] : 0 ;	//1mall平台抵用券支付金额
		$subtract_money   = isset($tradeInfo['orderDetail']['orderPromotionDiscount']) ? $tradeInfo['orderDetail']['orderPromotionDiscount'] : 0 ;	//参加促销活动立减金额
		
		$deliver_array = array( 
				'pcustID' 	 => $pcustID ,
				'creator' 	 => 'system' ,
				'custName'	 => $receiver_name,
				'provinceid' => 0 ,
				'province' 	 => $deliver_province ,
				'cityid' 	 => 0 ,
				'city'		 => $receiver_city,
				'countyid' 	 => 0,
				'county' 	 => $receiver_county ,
				'postalCode' => '' ,
				'address' 	 => $deliver_address ,
				'mobile' 	 => $receiver_mobile ,
				'phone' 	 => $receiver_phone
		) ;	
		//地址转化
		$this->receiverAddress($deliver_array) ;
		
		//==============================================生成配送方式号================================
		
		//如果有省，市，区则直接修改地址
		$get_custdeliver = new entity('cust_deliver') ;
		$get_custdeliver->pcustID 	 = $deliver_array ['pcustID'] ;
		$get_custdeliver->provinceid = $deliver_array ['provinceid'] ;
		$get_custdeliver->cityid     = $deliver_array ['cityid'] ;
		$get_custdeliver->countyid   = $deliver_array ['countyid'] ;
		if($this->dbca->fetch ($get_custdeliver)){
			$deliver_array ['deliverID'] = $get_custdeliver->deliverID ;
		}	
		//修改会员的配送地址	
		$deliverMsg = $custHandler->editCustDeliver($deliver_array);
		if($deliverMsg['code'] != 200){ 
			$deliverID = 4 ;							//如果找不到配送信息则直接默认配送方式 
		}else{
			$deliverID = $deliverMsg['data']['deliverID'] ;
		}
		//=============================================发票处理====================================
	
		$invoice_type	    = 1 ;						//普通发票类型
		$invoice_title_type	= 1 ;						//发票抬头类型
		$invoice_title		= '' ;						//发票抬头
		
		if($invoice != 0){
			$invoice_title = trim($invoiceArray['invoiceTitle']);
			if($invoice_title == '个人'){
				$invoice_title_type = 1 ;
			}else{
				$invoice_title_type = 2 ;
			}
		}
		//==============================================组成订单数组==============================
		   				
		$billArray = array() ;
		$billArray['pcustID'] = $pcustID ;	
		$billArray['custID']  = $custID ;	
		$billArray['master']  = array(
				 'deliverid' 			=> $deliverID,
				 'bill_subtract_money'  => $subtract_money ,
				 'bill_coupon_money'  	=> $coupon_money ,
				 'bill_card_money'  	=> 0 ,
				 'deliver_province' 	=> $deliver_array ['province'] ,
				 'deliver_city'			=> $deliver_array ['city'] ,
				 'deliver_county'		=> $deliver_array ['county'] ,
				 'deliver_address'		=> $deliver_array ['address'] ,
				 'deliver_postalCode'	=> $deliver_array ['postalCode'] ,
				 'deliver_name'			=> $deliver_array ['custName'] ,
				 'deliver_mobile'		=> $deliver_array ['mobile'] ,
				 'deliver_phone'		=> $deliver_array ['phone'] ,
				 'countyid'				=> $deliver_array ['countyid'] ,
				 'cityid'				=> $deliver_array ['cityid'] ,
				 'provinceid'			=> $deliver_array ['provinceid'] ,
				 'billType'				=> 4 ,
				 'extCustID'			=> $buyer_nick ,
				 'remark'				=> $order_remark,
				 'shopCode'				=> $shopCode ,
				 'deliver_send_time_id'   => 30 ,
				 'deliver_send_time_name' => '工作日、双休日与假日均可送货' ,
				 'invoice' 				=> $invoice,
				 'invoice_title_type'	=> $invoice_title_type,
				 'invoice_title'		=> $invoice_title,
				 'invoice_content' 		=> $invoice_title,
		) ;
									
		$billArray['bill_no'] 	  		= '';																			//订单号
		$billArray['bill_status'] 		= 0;																			//订单状态
		$billArray['goods']['general']  = array();																		//订单商品
		$billArray['tid'] 	  	  		= $order_id;																	//交易号
		$billArray['pay_time'] 	  		= $payment_time;																//支付时间
		$billArray['pay_code']   		= '';																			//订单支付码
		$billArray['totalMoney'] 		= $totalPrice ;																	//订单商品金额
		$billArray['totalPaid']   		= $payment;																		//订单实付金额
		$billArray['post_fee']    		= $freightPrice;																//订单邮费
		$billArray['vender_remark']   	= $vender_remark;																//商家留言
		
		//订单商品处理
		if($item_list) {
			$goodsHandler = new goodsHandler();
			foreach($item_list as &$g_l){
				//得到第三方商品编码
				$goodsCode = isset($g_l['outerId'])? $g_l['outerId'] : '' ;
				$goodsInfo = $this->get_trades_goods('8000500005026') ;
				
				//订单商品处理
				if($goodsInfo){
					$goodsInfo = $goodsInfo[0] ;
					$billArray['goods']['general'][] = array('goodsID' 		=> $goodsInfo->goodsID ,
															'postID'  		=> $goodsInfo->postID ,
															'goodsName'  	=> $g_l['productCName'],
															'spec'  	 	=> '',
															'goods_amount'  => $g_l['orderItemNum'] ,		//数量
															'salePrice'  	=> $g_l['originalPrice'],		//原价格
															'price'  		=> $g_l['orderItemPrice'],		//单价
															'marketPrice' 	=> $g_l['originalPrice'],
															'addPoints'  	=> 0,
															'salePoints'  	=> 0,
															'goodsWeight'  	=> 0,
															'goods_from'  	=> 1 ,
															'goods_groupID' => 0,
															'goods_status'  => 1,
															'img_link'  	=> $goodsHandler->setImgLink($goodsInfo->goodsMainPic),
															'link'  		=> $goodsHandler->setLink($goodsInfo->uid),
															'wap_link'  	=> $goodsHandler->setWapLink($goodsInfo->uid),
															'bigCategoryID' => $goodsInfo->bigCategoryID,
															'midCategoryID' => $goodsInfo->midCategoryID,
															'smallCategoryID' => $goodsInfo->smallCategoryID,
															'product_code' 	=> $goodsCode ,
															'twoPostID' 	=> $goodsInfo->twoPostID,
															'promotion' 	=> array(),
															) ;
				}else {
					return array('code' => 400 ,'message' => sprintf('交易号「%s」的商品编码「%s」商品不存在' , $order_id , $goodsCode)) ;
				}
			}
		}

		//=============================================配送方式=================================

		//如果配送方式找不到则默认一个配送方式
		if(!isset($billArray['master']['sendTypeID'])){
			$billArray['master']['sendTypeID'] 	  	 = DELIVERID ;		
			$billArray['master']['send_region_id'] 	 = 10 ;	
			$billArray['master']['send_region_name'] = '全国' ;
			$billArray['master']['sendTypeName'] 	 = '快递';
		}
		//==============================================支付方式保存================================
		
		if($pay_type == 2) {
			//货到付款标志
			$billArray['master']['pay_type'] 	= 1;
            $billArray['master']['payTypeID']   = 1;
            $billArray['master']['payTypeName'] = '货到付款';
            $billArray['master']['pay_status']	= 0;
		}else{
			$billArray['master']['pay_type'] 	= 2;
            $billArray['master']['payTypeID']   = EXTPAY;
            $billArray['master']['payTypeName'] = '第三方平台支付';
            $billArray['master']['pay_status']	= 1;
		}	
		return array('code' => 200 ,'message' => $billArray) ;
	}
	
	
	//格式化QQ交易接口
	public function QQtradeFormat($shopID , $shopCode , $tradeInfo){
		//参数判断
		if(!isset($tradeInfo['dealCode'] , $tradeInfo['dealPayFeeTotal'] , $tradeInfo['totalCash'] , $tradeInfo['itemList'])){
			return array('code' => 400 ,'message' => '交易数据格式错误') ;
		}
		$modified 	= isset($tradeInfo['lastUpdateTime']) ?  $tradeInfo['lastUpdateTime'] : '' ;							//交易最后修改时间
		$order_id 	= isset($tradeInfo['dealCode']) ?  $tradeInfo['dealCode'] : '' ;										//交易号
		$pay_type   = isset($tradeInfo['dealPayType']) ?  $tradeInfo['dealPayType'] : '' ;									//支付方式
		$totalPrice = isset($tradeInfo['dealPayFeeTotal']) ?  $tradeInfo['dealPayFeeTotal'] : 0 ;							//费用合计,一共要付的钱
		$payment 	= isset($tradeInfo['totalCash']) ?  $tradeInfo['totalCash'] : 0 ;										//总支付现金
		$order_remark  = isset($tradeInfo['buyerRemark']) ?  $tradeInfo['buyerRemark'] : '' ;								//买家下单时订单备注
		$order_time	   = isset($tradeInfo['createTime']) ?  $tradeInfo['createTime'] : '' ;									//下单时间
		$invoice	   = isset($tradeInfo['hasInvoice']) ?  $tradeInfo['hasInvoice'] : 0;									//是否有发票
		$invoiceContent = isset($tradeInfo['invoiceContent']) ?  $tradeInfo['invoiceContent'] : '' ;						//发票内容
		$invoiceTitle  = isset($tradeInfo['invoiceTitle']) ?  $tradeInfo['invoiceTitle'] : '' ;								//发票标题
		$feeType 	   = isset($tradeInfo['whoPayShippingfee']) ?  $tradeInfo['whoPayShippingfee'] : 2;						//承担运费方式: 1卖家;2买家
		$freightPrice  = isset($tradeInfo['freight']) ?  $tradeInfo['freight'] : 0 ;										//交易运费
		if($feeType == 1){
			$freightPrice = 0;
		}
		$payment = $payment - $freightPrice ; 
		
		//商品列表
		$item_list	   = isset($tradeInfo['itemList'])? $tradeInfo['itemList'] : array() ;	
		$vender_remark = isset($tradeInfo['dealNote']) ?  $tradeInfo['dealNote'] :'' ;										//商家订单备注（不大于500字符）
		$pay_time  	   = isset($tradeInfo['payTime']) ? $tradeInfo['payTime'] :'' ; 										//支付时间
		$pay_code      = isset($tradeInfo['tenpayCode'])?$tradeInfo['tenpayCode']: '' ;										//订单支付码
		$buyer_nick	   = isset($tradeInfo['buyerUin']) ? $tradeInfo['buyerUin'] : 'fk' . time(); 							//买家QQ号
		//买家名称
		$buyerName	   = isset($tradeInfo['buyerName']) && $tradeInfo['buyerName'] !='' ? $tradeInfo['buyerName'] : $buyer_nick;							
		$subtract_money = isset($tradeInfo['couponFee']) ? $tradeInfo['couponFee'] : 0;										//折扣优惠金额
		$coupon_money   = isset($tradeInfo['dealPayFeeTicket']) ? $tradeInfo['dealPayFeeTicket'] : 0;						//财付券支付金额
		
		//============================================会员信息处理===========================================
		
		$custHandler = new customerHandler($this->dbca) ;
		$custID 	 = $buyer_nick . '@qq.com' ;							//会员名称
		$reg_array 	 = array('custID' => $custID) ;							//查询参数
		$custInfo  	 = $custHandler->getCustomerInfo($reg_array) ;
		if(!$custInfo){
			//注册成新会员 , 随机密码
			$passwd = rand(1111111, 9999999) ;					
			$reg_array = array( 'regName'  => $custID ,
								 'regPwd'   => $passwd ,
								 'regPwd2'  => $passwd ,
								 'custType' => 1) ;
								 			 	 
			$custInfo = $custHandler->addCustomer($reg_array) ;
			if($custInfo['code'] == 200){
				//保存第三方会员和官网对应关系 
				$pcustID = $custInfo['data']['pcustID'] ;
				$this->save_3rdCust_rel($custID , $pcustID , $buyer_nick , $shopID) ;
			}else{
				return array ('code' => $custInfo['code'] , 'message' => $custInfo['message']) ;
			}
		}else{
			$pcustID = $custInfo[0]['pcustID'] ;
		}
		
		//=====================================配送信息处理======================================
		$receiver_name 	  = $tradeInfo['receiverName'] ;															//收货人
		$receiver_mobile  = isset($tradeInfo['receiverMobile']) ? $tradeInfo['receiverMobile'] : '' ;				//手机号
		$receiver_phone   = isset($tradeInfo['receiverPhone']) ? $tradeInfo['receiverPhone'] : '' ;					//电话号
		$deliver_province = isset($tradeInfo['province']) ? $tradeInfo['province'] : '' ;							//省
		$receiver_city	  = isset($tradeInfo['city']) ? $tradeInfo['city'] : '' ;									//市
		$receiver_county  = isset($tradeInfo['county']) ? $tradeInfo['county'] : '' ;								//区
		$deliver_address  = isset($tradeInfo['receiverAddress']) ? $tradeInfo['receiverAddress'] : '' ;				//地址
		$receiver_post	  = isset($tradeInfo['receiverPostcode']) ? $tradeInfo['receiverPostcode'] : '' ;			//邮编
		
		$deliver_array = array( 'pcustID' 	 => $pcustID,
								'creator' 	 => 'system' ,
								'custName'	 => $receiver_name,
								'provinceid' => 0,
								'province' 	 => $deliver_province ,
								'cityid' 	 => 0,
								'city'		 => $receiver_city,
								'countyid' 	 => 0,
								'county' 	 => $receiver_county,
								'postalCode' => $receiver_post,
								'address' 	 => $deliver_address,
								'mobile' 	 => $receiver_mobile,
								'phone' 	 => $receiver_phone) ;
		
		
		//地址转化
		$this->receiverAddress($deliver_array , 2) ;
		
		//==============================================生成配送方式号================================
		
		//如果有省，市，区则直接修改地址
		$get_custdeliver = new entity('cust_deliver') ;
		$get_custdeliver->pcustID 	 = $deliver_array ['pcustID'] ;
		$get_custdeliver->provinceid = $deliver_array ['provinceid'] ;
		$get_custdeliver->cityid     = $deliver_array ['cityid'] ;
		$get_custdeliver->countyid   = $deliver_array ['countyid'] ;
		if($this->dbca->fetch ($get_custdeliver)){
			$deliver_array ['deliverID'] = $get_custdeliver->deliverID ;
		}	
		//修改会员的配送地址	
		$deliverMsg = $custHandler->editCustDeliver($deliver_array);
		if($deliverMsg['code'] != 200) {
			$deliverID = 4 ;						//如果找不到配送信息则直接默认配送方式 
		}else{
			$deliverID = $deliverMsg['data']['deliverID'] ;
		}
		//==============================================组成订单数组==============================
		   				
		$billArray = array() ;
		$billArray['pcustID'] = $pcustID ;	
		$billArray['custID']  = $custID ;	
		$billArray['master']  = array('deliverid' 			=> $deliverID,
									 'bill_subtract_money'  => $subtract_money ,
									 'bill_coupon_money'  	=> $coupon_money ,
									 'bill_card_money'  	=> 0 ,
									 'deliver_province' 	=> $deliver_array ['province'] ,
									 'deliver_city'			=> $deliver_array ['city'] ,
									 'deliver_county'		=> $deliver_array ['county'] ,
									 'deliver_address'		=> $deliver_array ['address'] ,
									 'deliver_postalCode'	=> $deliver_array ['postalCode'] ,
									 'deliver_name'			=> $deliver_array ['custName'] ,
									 'deliver_mobile'		=> $deliver_array ['mobile'] ,
									 'deliver_phone'		=> $deliver_array ['phone'] ,
									 'countyid'				=> $deliver_array ['countyid'] ,
									 'cityid'				=> $deliver_array ['cityid'] ,
									 'provinceid'			=> $deliver_array ['provinceid'] ,
									 'billType'				=> 5 ,
									 'extCustID'			=> $buyerName ,
									 'remark'				=> $order_remark,
									 'shopCode'				=> $shopCode ,
									 'deliver_send_time_id'   => 30 ,
									 'deliver_send_time_name' => '工作日、双休日与假日均可送货' ,
									 'invoice' 				=> $invoice,
									 'invoice_title_type'	=> 1,
									 'invoice_title'		=> $invoiceTitle,
									 'invoice_content' 		=> $invoiceContent,
									) ;
									
		$billArray['bill_no'] 	  		= '';																			//订单号
		$billArray['bill_status'] 		= 0;																			//订单状态
		$billArray['goods']['general']  = array();																		//订单商品
		$billArray['tid'] 	  	  		= $order_id;																	//交易号
		$billArray['pay_time'] 	  		= $pay_time;																	//支付时间
		$billArray['pay_code']   		= $pay_code;																	//订单支付码	
		$billArray['totalMoney'] 		= ($totalPrice / 100) ;															//订单商品金额
		$billArray['totalPaid']   		= ($payment / 100) ;															//订单实付金额
		$billArray['post_fee']    		= ($freightPrice / 100); 														//订单邮费
		$billArray['vender_remark']   	= $vender_remark;																//商家留言
		
		//订单商品处理
		if($item_list) {
			$goodsHandler = new goodsHandler();
			foreach($item_list as &$g_l){
				//得到第三方商品编码
				$goodsCode = isset($g_l['itemLocalCode'])? $g_l['itemLocalCode'] : '' ;
				$goodsInfo = $this->get_trades_goods('8000500005026') ;
				
				//订单商品处理
				if($goodsInfo){
					$goodsInfo = $goodsInfo[0] ;
					$billArray['goods']['general'][] = array('goodsID' 		=> $goodsInfo->goodsID ,
															'postID'  		=> $goodsInfo->postID ,
															'goodsName'  	=> $g_l['itemName'],
															'spec'  	 	=> '' ,
															'goods_amount'  => $g_l['itemDealCount'] ,					//商品数量
															'salePrice'  	=> ($g_l['itemRetailPrice'] / 100) ,		//平台原价
															'price'  		=> ($g_l['itemDealPrice'] / 100 ) ,			//买家下单时的商品价格
															'marketPrice' 	=> ($g_l['itemRetailPrice'] / 100),
															'addPoints'  	=> 0 ,
															'salePoints'  	=> 0 ,
															'goodsWeight'  	=> 0 ,
															'goods_from'  	=> 1 ,
															'goods_groupID' => 0,
															'goods_status'  => 1,
															'img_link'  	=> $goodsHandler->setImgLink($goodsInfo->goodsMainPic),
															'link'  		=> $goodsHandler->setLink($goodsInfo->uid),
															'wap_link'  	=> $goodsHandler->setWapLink($goodsInfo->uid),
															'bigCategoryID' => $goodsInfo->bigCategoryID,
															'midCategoryID' => $goodsInfo->midCategoryID,
															'smallCategoryID' => $goodsInfo->smallCategoryID,
															'product_code' 	=> $goodsCode ,
															'twoPostID' 	=> $goodsInfo->twoPostID,
															'promotion' 	=> array(),
															) ;
				}else {
					return array('code' => 400 ,'message' => sprintf('交易号「%s」的商品编码「%s」商品不存在' , $order_id , $goodsCode)) ;
				}
			}
		}

		//=============================================配送方式=================================

		//如果配送方式找不到则默认一个配送方式
		if(!isset($billArray['master']['sendTypeID'])){
			$billArray['master']['sendTypeID'] 	  	 = DELIVERID;		
			$billArray['master']['send_region_id'] 	 = 10 ;	
			$billArray['master']['send_region_name'] = '全国' ;
			$billArray['master']['sendTypeName'] 	 = '快递';
		}
		
		//==============================================支付方式保存================================
		
		if($pay_type == 'TENPAY' || $pay_type == 'WEIXIN_PAY') {
			$billArray['master']['pay_type'] 	= 2;
            $billArray['master']['payTypeID']   = QQPAY;
            $billArray['master']['payTypeName'] = '财付通';
            $billArray['master']['pay_status']	= 1;
		}else{
			//货到付款标志
			$billArray['master']['pay_type'] 	= 1;
            $billArray['master']['payTypeID']   = 1;
            $billArray['master']['payTypeName'] = '货到付款';
            $billArray['master']['pay_status']	= 0;
		}	
		return array('code' => 200 ,'message' => $billArray) ;
	}
	
	//当当网订单格式化
	public function DDtradeFormat($shopID , $shopCode , $tradeInfo) {
		//参数判断
		if(!isset($tradeInfo->buyerInfo->goodsMoney , $tradeInfo->buyerInfo->totalBarginPrice, $tradeInfo->sendGoodsInfo , $tradeInfo->ItemsList->ItemInfo)){
			return array('code' => 400 ,'message' => '交易数据格式错误') ;
		}
		
		$operateList = $tradeInfo->OrderOperateList->OperateInfo ;
		
		//交易最后修改时间
		$modified 	= isset($tradeInfo->lastModifyTime) ? trim((string)$tradeInfo->lastModifyTime) : '' ;		
		//交易号											
		$order_id 	= isset($tradeInfo->orderID) ?  trim((string)$tradeInfo->orderID) : '' ;																
		//本订单商家应收金额
		$totalPrice = isset($tradeInfo->buyerInfo->goodsMoney) ?  trim((string)$tradeInfo->buyerInfo->goodsMoney) : 0 ;		
		//顾客需为订单支付现金
		$payment 	= isset($tradeInfo->buyerInfo->totalBarginPrice) ? trim((string)$tradeInfo->buyerInfo->totalBarginPrice) : 0 ;	
		//订单留言
		$order_remark  = isset($tradeInfo->message) ? trim((string)$tradeInfo->message) : '' ;											
		//是否有发票
		$invoice	= isset($tradeInfo->receiptInfo->Is_DangdangReceipt) ? trim((int)$tradeInfo->receiptInfo->Is_DangdangReceipt) : 1;	
		//发票内容								
		$invoiceContent = isset($tradeInfo->receiptInfo->receiptDetails) ? trim((string)$tradeInfo->receiptInfo->receiptDetails) : '' ;						
		//发票标题
		$invoiceTitle  = isset($tradeInfo->receiptInfo->receiptName) ? trim((string)$tradeInfo->receiptInfo->receiptName) : '' ;		
		//交易运费					
		$freightPrice  = isset($tradeInfo->postage) ? trim((string)$tradeInfo->postage) : 0 ;												
		$pay_type= isset($tradeInfo->buyerInfo->buyerPayMode) ? trim((string)$tradeInfo->buyerInfo->buyerPayMode) : '在线支付';					
		$payment = $payment - $freightPrice ; 
		
		//商品列表
		$itemLen = count($tradeInfo->ItemsList->ItemInfo) ;
		$item_list = array() ;
		if($itemLen == 1){
			$item_list [] = $tradeInfo->ItemsList->ItemInfo ;
		}else{
			$item_list = $tradeInfo->ItemsList->ItemInfo ;
		}

		//商家订单备注
		$vender_remark = isset($tradeInfo->remark) ?  trim((string)$tradeInfo->remark) :'' ;										
		//买家名称
		$buyer_nick	   = isset($tradeInfo->sendGoodsInfo->dangdangAccountID) ? md5(trim((string)$tradeInfo->sendGoodsInfo->dangdangAccountID)) : 'fk_'.time();		
		//网银支付满额减优惠金额				
		$subtract_money = isset($tradeInfo->buyerInfo->deductAmount) ? trim((string)$tradeInfo->buyerInfo->deductAmount) : 0;	
		//促销优惠金额
		$promoAmount   = isset($tradeInfo->buyerInfo->promoDeductAmount) ? trim((string)$tradeInfo->buyerInfo->promoDeductAmount) : 0;	
		$subtract_money += $promoAmount ;
		 
		//财付券支付金额						
		$coupon_money   = isset($tradeInfo->buyerInfo->giftCertMoney) ? trim((string)$tradeInfo->buyerInfo->giftCertMoney) : 0;		
		$giftCardMoney	= isset($tradeInfo->buyerInfo->giftCardMoney) ? trim((string)$tradeInfo->buyerInfo->giftCardMoney) : 0;		
		$pay_code		= '' ;
		$pay_time		=  isset($tradeInfo->paymentDate) ? (string)$tradeInfo->paymentDate : '';
		
		//============================================会员信息处理===========================================
		
		$custHandler = new customerHandler($this->dbca) ;
		$custID 	 = $buyer_nick . '@dd.com' ;							//会员名称
		$reg_array 	 = array('custID' => $custID) ;							//查询参数
		$custInfo  	 = $custHandler->getCustomerInfo($reg_array) ;
		if($pay_time == ''){
			//订单操作列表
			$opeLen = count($operateList) ;
			for($o = 0 ; $o < $opeLen ; $o++) {
				$operates = $operateList[$o]->operateDetails;
				if(stripos($operates , '已付款')){
					$pay_time = (string)$operateList[$o]->operateTime;
				}
			}
		}
		
		//检查会员是否存在
		if(!$custInfo){
			//注册成新会员 , 随机密码
			$passwd	   = rand(1111111, 9999999) ;					
			$reg_array = array( 'regName'  => $custID ,
								 'regPwd'   => $passwd ,
								 'regPwd2'  => $passwd ,
								 'custType' => 1) ;
								 			 	 
			$custInfo = $custHandler->addCustomer($reg_array) ;
			if($custInfo['code'] == 200){
				//保存第三方会员和官网对应关系 
				$pcustID = $custInfo['data']['pcustID'] ;
				$this->save_3rdCust_rel($custID , $pcustID , $buyer_nick , $shopID) ;
			}else{
				return array ('code' => $custInfo['code'] , 'message' => $custInfo['message']) ;
			}
		}else{
			$pcustID = $custInfo[0]['pcustID'] ;
		}	
		//=====================================配送信息处理======================================
		
		//收货人
		$receiver_name 	  = trim((string)$tradeInfo->sendGoodsInfo->consigneeName) ;										
		//手机号
		$receiver_mobile  = isset($tradeInfo->sendGoodsInfo->consigneeMobileTel) ? trim((string)$tradeInfo->sendGoodsInfo->consigneeMobileTel) : '' ;
		//电话号				
		$receiver_phone   = isset($tradeInfo->sendGoodsInfo->consigneeTel) ? trim((string)$tradeInfo->sendGoodsInfo->consigneeTel) : '' ;		
		//省			
		$deliver_province = isset($tradeInfo->sendGoodsInfo->consigneeAddr_Province) ? trim((string)$tradeInfo->sendGoodsInfo->consigneeAddr_Province) : '' ;		
		//市					
		$receiver_city	  = isset($tradeInfo->sendGoodsInfo->consigneeAddr_City) ? trim((string)$tradeInfo->sendGoodsInfo->consigneeAddr_City) : '' ;		
		//区							
		$receiver_county  = isset($tradeInfo->sendGoodsInfo->consigneeAddr_Area) ? trim((string)$tradeInfo->sendGoodsInfo->consigneeAddr_Area) : '' ;		
		//地址						
		$deliver_address  = isset($tradeInfo->sendGoodsInfo->consigneeAddr) ? trim((string)$tradeInfo->sendGoodsInfo->consigneeAddr) : '' ;		
		
		//去除地址中的省市区
		$addressArray = explode('，' , $deliver_address) ;
		$addressLen   = count($addressArray) ;
		$deliver_address = $addressArray [$addressLen-2] . $addressArray [$addressLen-1] ;
		
		//邮编		
		$receiver_post	  = isset($tradeInfo->sendGoodsInfo->consigneePostcode) ? trim((string)$tradeInfo->sendGoodsInfo->consigneePostcode) : '' ;			
		
		$deliver_array = array( 'pcustID' 	 => $pcustID,
								'creator' 	 => 'system' ,
								'custName'	 => $receiver_name,
								'provinceid' => 0,
								'province' 	 => $deliver_province ,
								'cityid' 	 => 0,
								'city'		 => $receiver_city,
								'countyid' 	 => 0,
								'county' 	 => $receiver_county,
								'postalCode' => $receiver_post,
								'address' 	 => $deliver_address,
								'mobile' 	 => $receiver_mobile,
								'phone' 	 => $receiver_phone) ;
		
		//地址转化
		$this->receiverAddress($deliver_array) ;
		
		//==============================================生成配送方式号================================
		
		//如果有省，市，区则直接修改地址
		$get_custdeliver = new entity('cust_deliver') ;
		$get_custdeliver->pcustID 	 = $deliver_array ['pcustID'] ;
		$get_custdeliver->provinceid = $deliver_array ['provinceid'] ;
		$get_custdeliver->cityid     = $deliver_array ['cityid'] ;
		$get_custdeliver->countyid   = $deliver_array ['countyid'] ;
		if($this->dbca->fetch ($get_custdeliver)){
			$deliver_array ['deliverID'] = $get_custdeliver->deliverID ;
		}	
		//修改会员的配送地址	
		$deliverMsg = $custHandler->editCustDeliver($deliver_array);
		if($deliverMsg['code'] != 200) {
			$deliverID = 4 ;								//如果找不到配送信息则直接默认配送方式 
		}else{
			$deliverID = $deliverMsg['data']['deliverID'] ;
		}
		//==============================================组成订单数组==============================
		   				
		$billArray = array() ;
		$billArray['pcustID'] = $pcustID ;	
		$billArray['custID']  = $custID ;	
		$billArray['master']  = array(
				 'deliverid' 			=> $deliverID,
				 'bill_subtract_money'  => $subtract_money ,
				 'bill_coupon_money'  	=> $coupon_money ,
				 'bill_card_money'  	=> 0 ,
				 'deliver_province' 	=> $deliver_array ['province'] ,
				 'deliver_city'			=> $deliver_array ['city'] ,
				 'deliver_county'		=> $deliver_array ['county'] ,
				 'deliver_address'		=> $deliver_array ['address'] ,
				 'deliver_postalCode'	=> $deliver_array ['postalCode'] ,
				 'deliver_name'			=> $deliver_array ['custName'] ,
				 'deliver_mobile'		=> $deliver_array ['mobile'] ,
				 'deliver_phone'		=> $deliver_array ['phone'] ,
				 'countyid'				=> $deliver_array ['countyid'] ,
				 'cityid'				=> $deliver_array ['cityid'] ,
				 'provinceid'			=> $deliver_array ['provinceid'] ,
				 'billType'				=> 11 ,
				 'extCustID'			=> $buyer_nick ,
				 'remark'				=> $order_remark,
				 'shopCode'				=> $shopCode ,
				 'deliver_send_time_id'   => 30 ,
				 'deliver_send_time_name' => '工作日、双休日与假日均可送货' ,
				 'invoice' 				=> $invoice,
				 'invoice_title_type'	=> 1,
				 'invoice_title'		=> $invoiceTitle,
				 'invoice_content' 		=> $invoiceContent,
		) ;
									
		$billArray['bill_no'] 	  		= '';																			//订单号
		$billArray['bill_status'] 		= 0;																			//订单状态
		$billArray['goods']['general']  = array();																		//订单商品
		$billArray['tid'] 	  	  		= $order_id;																	//交易号
		$billArray['pay_time'] 	  		= $pay_time;																	//支付时间
		$billArray['pay_code']   		= $pay_code;																	//订单支付码	
		$billArray['totalMoney'] 		= $totalPrice ;																	//订单商品金额
		$billArray['totalPaid']   		= $payment;																		//订单实付金额
		$billArray['post_fee']    		= $freightPrice;																//订单邮费
		$billArray['vender_remark']   	= $vender_remark;																//商家留言
		
		//订单商品处理
		$goodsHandler = new goodsHandler();
		for($i = 0 ; $i < $itemLen ; $i++){
			//得到第三方商品编码
			$goodsCode = isset($item_list[$i]->outerItemID)? trim((string)$item_list[$i]->outerItemID) : '' ;
			$goodsInfo = $this->get_trades_goods('8000500005026') ;
			
			//订单商品处理
			if($goodsInfo){
				$goodsInfo = $goodsInfo[0] ;
				$billArray['goods']['general'][] = array('goodsID' 		=> $goodsInfo->goodsID ,
														'postID'  		=> $goodsInfo->postID ,
														'goodsName'  	=> trim((string)$item_list[$i]->itemName) , 
														'spec'  	 	=> '' ,
														'goods_amount'  => trim((int)$item_list[$i]->orderCount) ,			//商品数量
														'marketPrice' 	=> trim((string)$item_list[$i]->marketPrice),		//市场价
														'salePrice'  	=> trim((string)$item_list[$i]->marketPrice) ,		//平台市场价格
														'price'  		=> trim((string)$item_list[$i]->unitPrice) ,		//商品单价
														'addPoints'  	=> 0 ,
														'salePoints'  	=> 0 ,
														'goodsWeight'  	=> 0 ,
														'goods_from'  	=> 1 ,
														'goods_groupID' => 0,
														'goods_status'  => 1,
														'img_link'  	=> $goodsHandler->setImgLink($goodsInfo->goodsMainPic),
														'link'  		=> $goodsHandler->setLink($goodsInfo->uid),
														'wap_link'  	=> $goodsHandler->setWapLink($goodsInfo->uid),
														'bigCategoryID' => $goodsInfo->bigCategoryID,
														'midCategoryID' => $goodsInfo->midCategoryID,
														'smallCategoryID' => $goodsInfo->smallCategoryID,
														'product_code' 	=> $goodsCode,
														'twoPostID' 	=> $goodsInfo->twoPostID,
														'promotion' 	=> array()) ;
			}else {
				return array('code' => 400 ,'message' => sprintf('交易号「%s」的商品编码「%s」商品不存在' , $order_id , $goodsCode)) ;
			}
		}
			
		//=============================================配送方式=================================

		//如果配送方式找不到则默认一个配送方式
		if(!isset($billArray['master']['sendTypeID'])){
			$billArray['master']['sendTypeID'] 	  	 = DELIVERID ;		
			$billArray['master']['send_region_id'] 	 = 10 ;	
			$billArray['master']['send_region_name'] = '全国' ;
			$billArray['master']['sendTypeName'] 	 = '快递';
		}
		
		//==============================================支付方式保存================================
		
		if($pay_type == '货到付款') {
			//货到付款标志
			$billArray['master']['pay_type'] 	= 1;
            $billArray['master']['payTypeID']   = 1;
            $billArray['master']['payTypeName'] = '货到付款';
            $billArray['master']['pay_status']	= 0;
		}else{
			$billArray['master']['pay_type'] 	= 2;
            $billArray['master']['payTypeID']   = EXTPAY;
            $billArray['master']['payTypeName'] = '第三方平台支付';
            $billArray['master']['pay_status']	= 1;
		}	
		

		return array('code' => 200 ,'message' => $billArray) ;
	}
	
	/**
	 * 第三方地址处理
	 *
	 * @param unknown_type $deliver_array
	 */
	public function receiverAddress(&$deliver_array , $channel=null){
		//QQ订单地址处理
		if($channel == 2) {
			$address 	= $deliver_array['address'] ;
			$addressArr = explode(' ' , $address) ;
			if(isset($addressArr[0]))						
				$deliver_array['province'] = $addressArr[0] ;				//省
			if(isset($addressArr[1]))
				$deliver_array['city'] = $addressArr[1] ;					//市
			if(isset($addressArr[2]))
				$deliver_array['county'] = $addressArr[2] ;					//区
			if(isset($addressArr[3]))
				$deliver_array['address'] = $addressArr[3] ;				//地址
		}
		
		//省参数处理
		if($deliver_array['province'] == '')
			$province = $deliver_array['province'] = '其他' ;
		else 
			$province = str_replace('省' , '', $deliver_array['province'] ) ;
		
		//市参数处理
		if($deliver_array['city'] == '')
			$city = $deliver_array['city'] = '其他' ;
		else 
			$city = str_replace('市' , '', $deliver_array['city'] ) ;
		
		//区参数处理
		if($deliver_array['county'] == '')
			$county = $deliver_array['county'] = '其他' ;
		else 
			$county = $deliver_array['county'] ;
		
		//省份处理
		$getProvince = $this->dbca->stmt_query("SELECT id,name FROM sys_region WHERE name LIKE '%$province%' AND region_level=1 ");
		if(!$getProvince){
			//找不到则新增
			$saveRegion = new entity('sys_region') ;
			$saveRegion->name 	  	  = $deliver_array['province']; 
			$saveRegion->parentID 	  = 0;
			$saveRegion->region_level = 1;
			$this->dbca->save($saveRegion , 'system') ;
			
			$deliver_array ['provinceid'] = $parentID = $this->dbca->insert_id ;
		}else
			$deliver_array ['provinceid'] = $parentID = $getProvince [0]->id ;
			
		//城市处理	
		$getCity = $this->dbca->stmt_query("SELECT id ,parentID, name  FROM  sys_region WHERE name LIKE '%$city%' AND parentID= $parentID AND region_level=2 ");
		if(!$getCity){
			//找不到则新增
			$saveRegion = new entity('sys_region') ;
			$saveRegion->name 	  	  = $deliver_array['city']; 
			$saveRegion->parentID 	  = $parentID;
			$saveRegion->region_level = 2;
			$this->dbca->save($saveRegion , 'system') ;
			
			$deliver_array ['cityid'] = $parentID = $this->dbca->insert_id ;
		}else
			$deliver_array ['cityid'] = $parentID = $getCity [0]->id ;
		
		//区域处理
		$getCounty 	 = $this->dbca->stmt_query("SELECT id ,parentID, name  FROM  sys_region WHERE name LIKE '%$county%' AND parentID= $parentID AND region_level=3");
		if(!$getCounty){
			//找不到则新增
			$saveRegion = new entity('sys_region') ;
			$saveRegion->name 	  	  = $deliver_array['county']; 
			$saveRegion->parentID 	  = $parentID;
			$saveRegion->region_level = 3;
			$this->dbca->save($saveRegion , 'system') ;
			$deliver_array ['countyid'] = $this->dbca->insert_id ;
		}else 	
			$deliver_array ['countyid'] = $getCounty [0]->id ;	
		
	}
	
	/**
	 * 得到类目属性
	 *
	 * @param unknown_type $propsArray		参数数组
	 * @param unknown_type $vflg			取属性值标志
	 * @return unknown
	 */
	public function getCateProps($propsArray , $vflg = 1) {
		//参数判读
		if(!isset($propsArray['shopID'] , $propsArray['cid'])){
			return array('code' => 400 , 'message' => '参数错误');
		}
		$p_pid = isset($propsArray['p_pid']) ? $propsArray['p_pid'] : 0 ;
		$p_vid = isset($propsArray['p_vid']) ? $propsArray['p_vid'] : 0 ;
	
		//返回父级属性
		$props = &$this->dbca->stmt_query('SELECT * FROM 3rd_props WHERE shopID=? AND cid=? AND p_pid=? AND p_vid=? AND is_sale !=1 ORDER BY is_color DESC ,sortOrder ASC' , 'siii' ,$propsArray['shopID'] , $propsArray['cid'] , $p_pid , $p_vid) ;
		
		if($props && $vflg == 1){
			foreach($props as &$p_l){
				//得到属性值 
				$pvInfo = &$this->dbca->stmt_query('SELECT vid,vname,alias,is_parent FROM 3rd_prop_value WHERE shopID=? AND cid=? AND pid=?' , 'sii' , $propsArray['shopID'], $propsArray['cid'],$p_l->pid) ;
				$p_l->values = $pvInfo;
			}
		}

		return $props ;
	}
	
	//类目属性列表处理
	public function propsList(&$params) {
		//sql字符串
		$sql = '';
		
		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//默认店铺
		if (!isset($params['shopID']) || empty($params['shopID'])){
			$params['shopID'] = 1 ;
		}
		
		$sql .= ' AND pr.shopID = ?';
		$params_type .= 's';
		$params_array[] = $params['shopID'];

		//属性号
		if (isset($params['pid']) &&  !empty($params['pid']) ) {
			$sql .= ' AND pr.pid = ?';
			$params_type .= 'i';
			$params_array[] = trim($params['pid']);
		}

		//属性值号
		if (isset($params['vid']) && !empty($params['vid'])) {
			$sql .= ' AND pv.vid = ?';
			$params_type .= 'i';
			$params_array[] = $params['vid'];
		}

		//属性
		if (isset($params['pname']) && !empty($params['pname'])) {
			$sql .= ' AND pr.pname = ? ';
			$params_type .= 's';
			$params_array[] = $params['pname'];
		}
		
		//属性值
		if (isset($params['vname']) && !empty($params['vname'])) {
			$sql .= ' AND pv.vname = ? ';
			$params_type .= 's';
			$params_array[] = $params['vname'];
		}

		if ($sql){
			$sql = 'WHERE ' . substr($sql, 4);
		}
		
		//分页字符串
		$limit = '';

		if (isset($params['rp']) && $params['rp'] > 1) {

			//排序
			if (isset($params['sortname']) && !empty($params['sortname'])){
				$limit .= sprintf(' ORDER BY pv.%s %s', $params['sortname'] , $params['sortorder']);
			}
			//分页
			if (!isset($params['page']) || !is_numeric($params['page']) || $params['page'] <= 0){
				$params['page'] = 1;
			}
			
			//统计数量
	        $search_sql  = 'SELECT COUNT(*) count FROM 3rd_props pr 
	        				INNER JOIN 3rd_shop sp on sp.shopID = pr.shopID
							LEFT JOIN `3rd_system_category` sc ON sc.`shopID` = pr.`shopID` AND sc.`cid` = pr.`cid`
							LEFT JOIN 3rd_prop_value pv ON pr.`shopID`=pv.`shopID` AND pr.cid=pv.cid AND pr.`pid`=pv.`pid` ' . $sql;
	        $count_array = $this->dbca->stmt_query($search_sql, $params_type, $params_array);
	        
			$params['count'] = $count_array[0]->count ;

			$limit .= sprintf(' LIMIT %d, %d', ($params['page'] - 1) * $params['rp'], $params['rp']);

		} else {
			//排序
			if (isset($params['sortname']) && !empty($params['sortname'])){
				$limit .= sprintf(' ORDER BY pv.%s %s', $params['sortname'] , $params['sortorder']);
			}
		}

        //查询商品属性信息
        $s_sql = 'SELECT pr.*,pv.`vid`,pv.`vname`, pv.is_parent , sc.`name` cateName , sp.title FROM 3rd_props pr 
				INNER JOIN 3rd_shop sp on sp.shopID = pr.shopID
				LEFT JOIN `3rd_system_category` sc ON sc.`shopID` = pr.`shopID` AND sc.`cid` = pr.`cid`
				LEFT JOIN 3rd_prop_value pv ON pr.`shopID`=pv.`shopID` AND pr.cid=pv.cid AND pr.`pid`=pv.`pid`  ' . $sql . $limit;

        $result = $this->dbca->stmt_query($s_sql, $params_type, $params_array);
        
        if(!$result){
        	return null ;
        }
        
        foreach($result as $val){
            $result_all[] = array(
            	'shopID'  => $val->shopID,
            	'title'	  => $val->title,
                'pname'   => $val->pname,
                'vname'   => $val->vname,
                'cid'	  => $val->cid,
                'cateName'=> $val->cateName,
                'pid' 	  => $val->pid,
                'vid'	  => $val->vid,
                'is_parent' => $val->is_parent,
            );
        }
        return $result_all;
	}
	
	
	
	/**
	 * 得到商品SKU
	 *
	 * @param unknown_type $product_code		商品编码
	 * @param unknown_type $product_mainID		商品主编码
	 */
	public function goodsSku($product_mainID , $product_code = null){
		if($product_code)
			$skuArray = &$this->dbca->stmt_query('SELECT * FROM goods_sale_edit WHERE product_mainID=? AND product_code=?' , 'ss' , $product_mainID , $product_code) ;
		else
			$skuArray = &$this->dbca->stmt_query('SELECT * FROM goods_sale_edit WHERE product_mainID=?' , 's' , $product_mainID) ;
		return 	$skuArray ;
	}
	
	/**
     * 保存价格历史记录
     * @param $arg_array
     */
    public function save_goods_history($arg_array){
        $price_history = new entity('3rd_price_history');
        $price_history->creator		 = $arg_array['creator'];
        $price_history->goodsCode 	 = $arg_array['goodsCode'];
        $price_history->product_code = $arg_array['product_code'];
        $price_history->product_name = $arg_array['product_name'];
        $price_history->salePrice 	 = $arg_array['salePrice'];
        $price_history->stockCount 	 = $arg_array['stockCount'];
        $price_history->shopID 		 = $arg_array['shopID'];
        $this->dbca->save($price_history);
    }
	
	/**
	 * 保存上传商品错误信息.
	 *
	 * @param unknown_type $creator				操作人
	 * @param unknown_type $product_code		宝贝编码
	 * @param unknown_type $err_msg				错误信息
	 * @param unknown_type $action				操作类型
	 * @param unknown_type $shopID				店铺号
	 */
	public function goodsFail ($shopID , $creator , $product_code , $action , $err_msg) {
		$goodsFail = new entity('3rd_goods_fail') ;
		$goodsFail->product_code = $product_code ;
		$goodsFail->err_msg = $err_msg ;
		$goodsFail->action  = $action ;
		$goodsFail->shopID  = $shopID ;
		$goodsFail->creator = $creator ;
		$this->dbca->save($goodsFail , '3rd') ;
	}
 	
	/**
	 * 更新商品
	 *
	 * @param unknown_type $itemCode	第三平台编码
	 * @param unknown_type $shopID		店铺号
	 * @param unknown_type $goodsCode	宝贝编码
	 */
	public function goodsUploadResult($itemCode , $shopID , $product_code){
		$this->dbca->stmt_query('UPDATE 3rd_goods_relation SET timeStamp=NOW() , modifiedTime=NOW() , goodsCode=? WHERE shopID=? AND product_code=?' , 'sss' , $itemCode ,  $shopID , $product_code) ;
	}
	
    /**
     * 交易监控
     */
    public function trademonitor(&$args){
        //sql字符串
        $sql = '';
    
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        $req_no   	= isset($args['req_no']) ? $args['req_no'] : 0;
        $order_id 	= isset($args['order_id']) ? $args['order_id'] : '';
        $shopID 	= isset($args['shopID']) ? $args['shopID'] : 0;
        $startDate 	= isset($args['startDate']) ? $args['startDate'] : '';
        $endDate 	= isset($args['endDate']) ? $args['endDate'] : '' ;
        
        //请求号
        if (isset($req_no) && !empty($req_no)) {
            $sql .= ' AND tf.req_no = ? ';
            $params_type .= 'i';
            $params_array[] = $req_no;
        }
        
        //交易号
        if (isset($order_id) && !empty($order_id)) {
            $sql .= ' AND tf.order_id = ? ';
            $params_type .= 's';
            $params_array[] = $order_id;
        }
        
        //店铺
        if (isset($shopID) && !empty($shopID)) {
            $sql .= ' AND tf.shopID = ? ';
            $params_type .= 'i';
            $params_array[] = $shopID;
        }
        
        //创建时间
        if (isset($startDate) && !empty($startDate)) {
            $sql .= ' AND tf.createTime >= ? ';
            $params_type .= 's';
            $params_array[] = $startDate;
        }
        
        if (isset($endDate) && !empty($endDate)) {
            $sql .= ' AND tf.createTime <= ? ';
            $params_type .= 's';
            $params_array[] = $endDate;
        }
        
        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        //分页字符串
        $limit = '';

        if (isset($args['rp']) && $args['rp'] > 1) {

            //排序
            if (isset($args['sortname']) && !empty($args['sortname']))
                $limit .= sprintf(' ORDER BY %s %s', $args['sortname'], $args['sortorder']);

            //分页
            if (!isset($args['page']) || !is_numeric($args['page']) || $args['page'] <= 0)
                $args['page'] = 1;

            $limit .= sprintf(' LIMIT %d, %d', ($args['page'] - 1) * $args['rp'], $args['rp']);

        } else {
            //排序
            if (isset($args['sortname']) && !empty($args['sortname']))
                $limit .= sprintf(' ORDER BY %s %s', $args['sortname'], $args['sortorder']);
        }
		
        //统计数量
        $count_sql = 'SELECT count(*) count FROM `3rd_trades_fail` tf LEFT JOIN `3rd_shop` sp ON tf.`shopID` = sp.`shopID`' . $sql;
        $count_arr = $this->dbca->stmt_query($count_sql , $params_type , $params_array);
		$args['count'] = $count_arr[0]->count;
		
        //查询信息
        $search_sql = 'SELECT tf.* , sp.title FROM `3rd_trades_fail` tf LEFT JOIN `3rd_shop` sp ON tf.`shopID` = sp.`shopID` ' . $sql . $limit;
        $result_all = $this->dbca->stmt_query($search_sql , $params_type , $params_array);

        return $result_all;
    }

    /**
     * 交易日志
     * @param $_REQUEST
     * @return mixed
     */
    public function tradelog(&$args){
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        $req_no	   = isset($args['req_no'])? $args['req_no'] : '';				//请求号
        $shopID    = isset($args['shopID'])? $args['shopID'] : '';				//店铺号
        $startDate = isset($args['startDate']) ? $args['startDate'] : '';		//开始时间
        $endDate   = isset($args['endDate']) ? $args['endDate'] : '';			//结果时间
        
        //请求号
        if (isset($req_no) && !empty($req_no)) {
            $sql .= ' AND tl.req_no = ? ';
            $params_type .= 'i';
            $params_array[] = $req_no;
        }
        
		//店铺号
        if (isset($shopID) && !empty($shopID)) {
            $sql .= ' AND tl.`shopID` = ? ';
            $params_type .= 's';
            $params_array[] = $shopID;
        }
        
        //创建时间
        if (isset($startDate) && !empty($startDate)) {
            $sql .= ' AND tl.createTime >= ? ';
            $params_type .= 's';
            $params_array[] = $startDate . ' 00:00:00';
        }
        if (isset($endDate) && !empty($endDate)) {
            $sql .= ' AND tl.createTime <= ? ';
            $params_type .= 's';
            $params_array[] = $endDate . ' 23:59:59';
        }
        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        //分页字符串
        $limit = '';

        if (isset($args['rp']) && $args['rp'] > 1) {

            //排序
            if (isset($args['sortname']) && !empty($args['sortname']))
                $limit .= sprintf(' ORDER BY %s %s', $args['sortname'], $args['sortorder']);

            //分页
            if (!isset($args['page']) || !is_numeric($args['page']) || $args['page'] <= 0)
                $_REQUEST['page'] = 1;

            $limit .= sprintf(' LIMIT %d, %d', ($args['page'] - 1) * $args['rp'], $args['rp']);

        } else {

            //排序
            if (isset($args['sortname']) && !empty($args['sortname']))
                $limit .= sprintf(' ORDER BY %s %s', $args['sortname'], $args['sortorder']);

        }

        //统计数量
        $count_sql = 'SELECT COUNT(*) count FROM 3rd_trades_log tl LEFT JOIN `3rd_shop` sp ON tl.`shopID` = sp.`shopID` ' . $sql;

        $count_arr = $this->dbca->stmt_query($count_sql , $params_type , $params_array);
		$args['count'] = $count_arr[0]->count ;

        //查询信息
        $search_sql = 'SELECT tl.req_no,tl.request_str, tl.request_flg,tl.request_type , sp.`title` FROM 3rd_trades_log tl LEFT JOIN `3rd_shop` sp  ON tl.`shopID` = sp.`shopID`' . $sql . $limit;
        $result_all = $this->dbca->stmt_query($search_sql, $params_type, $params_array);
       
        return $result_all;
    }

	
	/**
	 * 订单发货
	 * 
	 * @param unknown_type $shopID			店铺号
	 * @param unknown_type $bill_no			订单号
	 * @param unknown_type $out_sid			运单号
	 * @param unknown_type $company_code	物流公司代码。
	 */
	public function logistics_send ($shopID , $bill_no , $out_sid , $company_code) {
		if($channel == 1) {
			$logistics = array('OTHER' 	=> '其他' ,
							   'POST' 	=> '中国邮政平邮' ,
							   'MGSD'	=> '美国速递' ,
							   'ZJS' 	=> '宅急送' ,
							   'YCT'	=> '黑猫宅急便' ,
							   'EYB'	=> 'EMS经济快递' ,
							   'NEDA' 	=> '港中能达',
							   'UC' 	=> '优速快递' ,
							   'FAST' 	=> '快捷速递',
							   'QFKD' 	=> '全峰快递',
							   'LB' 	=> '龙邦速递',
							   'SF' 	=> '顺丰速运',
							   'FEDEX' 	=> '联邦快递',
							   'UAPEX' 	=> '全一快递',
							   'ZTO' 	=> '中通速递',
							   'TTKDEX' => '天天快递',
							   'YTO' 	=> '圆通速递',
							   'YUNDA' 	=> '韵达快运',
							   'STO' 	=> '申通E物流',
							   'EMS' 	=> 'EMS',
							   'HTKY' 	=> '百世汇通',
							  ) ;

			if (! isset($logistics[$company_code])){
				return array('code' => 400 , 'message' => '物流公司不存在') ;
			}
			
			//得到天猫交易信息
			$getTidInfo = new entity('3rd_trades') ;				
			$getTidInfo->shopID  = $shopID ;
			$getTidInfo->bill_no = $bill_no ;
			if(!$this->dbca->fetch($getTidInfo)){
				return array('code' => 404 , 'message' => '订单对应的天猫交易不存在') ;
			}
			$tid = $getTidInfo->order_id ; 
			
			//更新ERP发货标志
			$resultFlg = $this->dbca->stmt_query('UPDATE 3rd_trades SET status=2 ,timestamp=NOW() WHERE shopID=? AND order_id=?' ,'si' , $shopID , $tid);
			if($resultFlg > 0) {
				$send_array = array('code' 	  => 100 ,
									'message' => 'trade_send' ,
									'data'    => array('tid'    	 => $tid, 
													   'outSid' 	 => $out_sid , 
													   'companyCode' => $company_code))  ;
													   
				$send_result = $this->pushMQ ($send_array , true) ;
				if($send_result['code'] == 200 && isset($send_result['data']['shipping']['is_success']) && $send_result['data']['shipping']['is_success']){
					$this->dbca->stmt_query('UPDATE 3rd_trades SET sendFlg=2 ,timestamp=NOW() WHERE channel=? AND order_id=?' ,'ii' , $channel , $tid);
					
					return array('code' => 200 , 'message' => '天猫发货成功') ;
				}else if(isset($send_result['data']['sub_msg'])){
					return array('code' => 400 , 'message' => $send_result['data']['sub_msg']) ;
				}
			}
			
			return array('code' => 500 , 'message' => '变更交易发货标志失败') ;
			
		}
		
	}
	
	
	/**
	 * 商品详情描述处理
	 *
	 * @param unknown_type $Desc
	 */
	public function goodsDesc ($description) {
		preg_match_all ('/(<img )(.[^>]*)(>)/', $description , $matchArray); 
		if(empty($matchArray)){
			return $description ;
		}
		//被截取的图片正则
		$picArray = $matchArray[0] ;
	
		if(!empty($picArray)){
			foreach ($picArray as &$p_l)  {
				//将图片打散
				$imgArr  	 = explode(' ', $p_l) ;
				$image_title = 'desc_' . make_uuid();
				if($imgArr) {
					foreach ($imgArr as &$i_l) {
						//将src 换成默认的图片路径
						if(stripos($i_l , 'src') !== false) {
							$srcArr1  = explode('"' , $i_l) ;
							$srcArr2  = explode("'" , $i_l) ;
							if(count($srcArr1) > 1) {
								$srcStr = $srcArr1[1] ;
							}else{
								$srcStr = $srcArr2[1] ;
							}	
							
							$img_array   = array('code'   => 100 ,
												'message' => 'img_upload' ,
												'data' 	  => array('picCate' 	 => 0,
																   'image' 	 	 => $srcStr , 
																   'title' 	 	 => $image_title , 
																   'image_title' =>  $image_title))  ;
																   
							$img_result = $this->pushMQ ($img_array , true) ;
							
							if($img_result['code'] == 200 && isset($img_result['data']['picture']['picture_path'])){
								$imgPath = $img_result['data']['picture']['picture_path'] ;
								//将图片重新放入到内容中
								$description = str_replace($srcStr , $imgPath , $description) ;
							}
						}
					}
				}
			}
		}

		//返回最新的详情
		return $description ;
	}


	/**
	 * 保存商品映射属性
	 *
	 * @param unknown_type $product_code	商品主编码
	 * @param unknown_type $cid				商品子类目号
	 * @param unknown_type $pid				商品属性号
	 * @param unknown_type $vid				商品属性值号
	 * @param unknown_type $value			属性值
	 * @param unknown_type $alias			属性值别名
	 * @param unknown_type $ptype			属性类型
	 * @param unknown_type $channel			渠道
	 */
    public function saveGoodsProps($product_code , $cid , $pid , $vid , $value , $alias , $ptype , $is_parent , $creator , $shopID , $postID = 0 , $num = 0 , $price = 0){
    	$saveProps = new entity('3rd_goods_props') ;
    	$saveProps->creator 	 = $creator;
    	$saveProps->product_code = $product_code;
    	$saveProps->postID		 = $postID;
    	$saveProps->num			 = $num;
    	$saveProps->price		 = $price;
    	$saveProps->cid 		 = $cid;
    	$saveProps->pid 		 = $pid;
    	$saveProps->vid 		 = $vid;
    	$saveProps->value 		 = $value;
    	$saveProps->alias 		 = $alias;
    	$saveProps->ptype 		 = $ptype;
    	$saveProps->is_parent 	 = $is_parent;
    	$saveProps->shopID 	 	 = $shopID;
    	$this->dbca->save($saveProps , '3rd') ;
    }
	

    /**
     * 得到所有商品属性
     *
     * @param unknown_type $channel			渠道号
     * @param unknown_type $product_code	商品编码
     */
    public function getGoodsProps($shopID , $product_code , $pid = null) {
    	if($pid != ''){
    		$propsArr = $this->dbca->stmt_query('SELECT * FROM 3rd_goods_props WHERE shopID=? AND product_code=? AND pid=? ORDER BY is_parent DESC ' , 'ssi' , $shopID , $product_code , $pid) ;
    	}else{
    		$propsArr = $this->dbca->stmt_query('SELECT * FROM 3rd_goods_props WHERE shopID=? AND product_code=? ORDER BY is_parent DESC ' , 'ss' , $shopID , $product_code) ;
    	}
    	return $propsArr ;
    }
    
    /**
     * 得到子属性串
     *
     * @param unknown_type $pid
     * @param unknown_type $vid
     * @param unknown_type $pidStr
     * @param unknown_type $vnameStr
     */
   	public function getChildProp ($shopID , $params , $cid ,&$fpid , &$fvid , &$child_pname , &$child_vname ,$ptype) {
   		global $G_PGLOB;
   		
   		//得到属性值信息
   		$fprops = $this->dbca->stmt_query('SELECT p.* ,v.vid,v.vname,v.is_parent FROM `3rd_props` p INNER JOIN `3rd_prop_value` v ON p.shopID=v.shopID AND p.cid=v.cid AND p.pid=v.pid 
   												 WHERE p.shopID=? AND p.cid=? AND p.pid=? AND v.vid=?' ,'iiii' , $shopID , $cid, $fpid , $fvid) ;

   		if(!$fprops || $fprops[0]->is_parent == 0){
   			return false ;
   		}
   		//得到子属性
   		$getpvInfo =  new entity('3rd_props') ;
   		$getpvInfo->shopID = $shopID;
   		$getpvInfo->cid    = $cid;
   		$getpvInfo->p_pid  = $fpid;
   		$getpvInfo->p_vid  = $fvid;
   		if(!$this->dbca->fetch($getpvInfo)){
   			return false ;
   		}
		$pid = $getpvInfo->pid ;
		if($ptype == 'key'){
			$vid   = isset($params['props']['key_prop_' . $pid]) ? $params['props']['key_prop_' . $pid] : 0 ;
			$vname = isset($params['props']['key_prop_custom_' . $pid]) ? trim($params['props']['key_prop_custom_' . $pid]) : '' ;
		}else{
			$vid   = isset($params['props']['prop_' . $pid]) ? $params['props']['prop_' . $pid] : 0 ;
			$vname = isset($params['props']['prop_custom_' . $pid]) ? trim($params['props']['prop_custom_' . $pid]) : '' ;
		}
		
		//得到子属性值信息
   		$childProps = $this->dbca->stmt_query('SELECT p.* ,v.vid,v.vname,v.is_parent FROM `3rd_props` p INNER JOIN `3rd_prop_value` v ON p.shopID=v.shopID AND p.cid=v.cid AND p.pid=v.pid 
   												  WHERE p.shopID=? AND p.cid=? AND p.pid=? AND v.vid=?' ,'iiii' , $shopID , $cid, $pid , $vid) ;

		//组串
		$child_pname = $getpvInfo->pname;
		$child_vname = $vname;
   		
		$fpid = $pid ;
		$fvid = $vid ;
		
		if(!$childProps || $childProps[0]->is_parent == 0){
			return false ;
		}
		return true ;
   	}
   	
    /**
     * 根据关键字查询属性值
     * @param array $arg_array                      查询参数数组
     * $arg_array = array (
            'forsale' => int 是否可销售
            'useFlg' => int 是否已下架
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchPropValue( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //上下架
        if (isset($arg_array['vid']) && !empty($arg_array['vid'])) {
            $sql .= ' AND vid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['vid'];
        }
        
        //渠道
        if (isset($arg_array['channel']) && !empty($arg_array['channel'])) {
            $sql .= ' AND channel = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['channel'];
        }
        
        //类目号
        if (isset($arg_array['cid']) && !empty($arg_array['cid'])) {
            $sql .= ' AND cid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cid'];
        }
        
        //属性号
        if (isset($arg_array['pid']) && !empty($arg_array['pid'])) {
            $sql .= ' AND pid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pid'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
		
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM 3rd_prop_value ' . $sql ;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }
				
                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY gl.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY gl.%s gl.%s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM 3rd_prop_value ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
			
            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'cid' => $item->cid,
                    'pid' => $item->pid,
                    'vid' => $item->vid,
                    'vname' => $item->vname,
                    'alias' => $item->alias,
                    'is_parent' => $item->is_parent,
                    'sortOrder' => $item->sortOrder,
                    'channel' => $item->channel
                );
            }

            if (isset($arg_array['postID']) || isset($arg_array['product_code'])) {
                return $item_array[0];
            } else {
                return $item_array;
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    public function searchShopCustomerList(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //店铺号
        if (isset($arg_array['shopID']) && !empty($arg_array['shopID'])) {
            $sql .= ' AND 3cr.shopID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['shopID'];
        }

        //渠道
        if (isset($arg_array['channelID']) && !empty($arg_array['channelID'])) {
            $sql .= ' AND 3c.channelID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['channelID'];
        }

        //平台会员名称
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
            $sql .= ' AND 3cr.custID like ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['custID'].'%';
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM 3rd_customer_relation 3cr LEFT JOIN 3rd_shop 3s ON 3cr.shopID = 3s.shopID LEFT JOIN 3rd_channel 3c ON 3s.channel = 3c.channelID ' . $sql ;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $sitem = '3cr.custID,3cr.pcustID,3cr.userName,3cr.shopID,3c.channelID,3c.channelName,3s.title';
            $search_sql = 'SELECT '.$sitem.'  FROM 3rd_customer_relation 3cr LEFT JOIN 3rd_shop 3s ON 3cr.shopID = 3s.shopID LEFT JOIN 3rd_channel 3c ON 3s.channel = 3c.channelID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'custID' => $item->custID,
                    'pcustID' => $item->pcustID,
                    'userName' => $item->userName,
                    'shopID' => $item->shopID,
                    'channelID' => $item->channelID,
                    'channelName' => $item->channelName,
                    'shopName' => $item->title
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /*宝贝价格对比列表
    * @create by allen.qiang
    * 返回数组
    * */
    public function goodsPrice_list(&$params){
        $sqlStr 	  = ' WHERE ';
        $params_type  = '';
        $params_array = array();

        //店铺
        if (isset($params['shopID']) && !empty($params['shopID'])) {
            $sqlStr 		.= ' op.shopID = ?';
            $params_type 	.= 'i';
            $params_array[]  = $params['shopID'];
        }else{
            $sqlStr 		.= ' op.shopID=1';
        }
        //宝贝编号
        if (isset($params['product_code']) && !empty($params['product_code'])) {
            $sqlStr .= ' AND op.product_code = ?';
            $params_type .= 's';
            $params_array[] = $params['product_code'];
        }

        //宝贝名称
        if (isset($params['goodsName']) && !empty($params['goodsName'])) {
            $sqlStr .= ' AND op.goodsName like ? ';
            $params_type .= 's';
            $params_array[] = '%'.$params['goodsName'].'%';
        }

        //分页字符串
        $limitStr = '';
        if (isset($params['rp']) && $params['rp'] > 1) {

            //排序
            if (isset($params['sortname']) && !empty($params['sortname'])){
                $limitStr .= sprintf(' ORDER BY gl.%s %s', $params['sortname'], $params['sortorder']);
            }
            //分页
            if (!isset($params['page']) || !is_numeric($params['page']) || $params['page'] <= 0){
                $params['page'] = 1;
            }
            $limitStr .= sprintf(' LIMIT %d, %d', ($params['page'] - 1) * $params['rp'], $params['rp']);
            //统计数量
            $count_sql = 'SELECT COUNT(DISTINCT(op.product_code)) count FROM `3rd_online_price` op ' . $sqlStr ;
            $listCount = $this->dbca->stmt_query($count_sql, $params_type, $params_array);
            $params['count'] = $listCount[0]->count ;
        } else {
            //排序
            if (isset($params['sortname']) && !empty($params['sortname'])){
                $limitStr .= sprintf(' ORDER BY gl.%s %s', $params['sortname'], $params['sortorder']);
            }
        }

        //查询宝贝价格
        $list_sql = 'SELECT DISTINCT op.product_code,op.goodsName ,op.marketPrice,op.shopID,sp.`title`,op.salePrice,op.onlinePrice
        FROM `3rd_online_price` op INNER JOIN `3rd_shop` sp ON sp.shopID=op.`shopID` ' . $sqlStr . $limitStr;
        $listArr  = $this->dbca->stmt_query($list_sql , $params_type, $params_array);
        if(!$listArr){
            return null ;
        }
        if($listArr){
            foreach($listArr as $val){
                $result[] = array(
                    'product_code' => $val->product_code,
                    'shopID' 	     => $val->shopID,
                    'goodsName'     => $val->goodsName,
                    'title' 	     => $val->title,
                    'marketPrice'  => $val->marketPrice,
                    'salePrice'    => $val->salePrice,//平台价格
                    'onlinePrice'  => $val->onlinePrice//销售价格
                );
            }
        }

        return $result;
    }

    /*
     * 系统价格下载更新
     * 返回状态数组
     * create by allen.qiang
     * */
    public function salePriceDownload(){

        //查询系统所有商品信息
        $list_sql = 'SELECT DISTINCT product_code,goodsName ,salePrice,marketPrice FROM 3rd_goods_relation';
        $listArr  = $this->dbca->stmt_query($list_sql);
        if(!$listArr){
            $result =  array('code'=>404, 'message' => '本地商品信息查询不到，请重试或者联系管理员');
        }else{
            //插入更新商品信息
            try{
                foreach($listArr as $val){
                    $obj = new entity('3rd_onsaleprice');
                    $obj->product_code = $val->product_code;
                    if($this->dbca->fetch($obj)){
                        $obj->goodsName    = $val->goodsName;
                        $obj->oldsalePrice = $val->salePrice;
                        $obj->price         = $val->marketPrice;
                    }else{
                        $obj->creator       = 'system';
                        $obj->product_code = $val->product_code;
                        $obj->goodsName    = $val->goodsName;
                        $obj->oldsalePrice = $val->salePrice;
                        $obj->price         = $val->marketPrice;
                    }
                    $this->dbca->save($obj);
                }
                $result =  array('code'=>200, 'message' => '本地商品信息更新成功');
            }catch(Exception $e){
                error_log( $e->getMessage() );
                echo json_encode( array('message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
                return;
            }
        }
        return $result;
    }

    /*
     * 平台商品价格下载更新
     * 返回状态数组
     * create by allen.qiang
     * */
    public function platformPrice(){

        $this->salePriceDownload();
        //查询平台所有商品信息
        $list_sql = 'SELECT DISTINCT product_code,goodsName ,salePrice,marketPrice FROM 3rd_goods_relation';
        $listArr  = $this->dbca->stmt_query($list_sql);
        if(!$listArr){
            $result =  array('code'=>404, 'message' => '平台商品信息查询不到，请重试或者联系管理员');
        }else{
            //插入更新商品信息
            try{
                foreach($listArr as $val){
                    $obj = new entity('3rd_onsaleprice');
                    $obj->product_code = $val->product_code;
                    if($this->dbca->fetch($obj)){
                        $obj->goodsName    = $val->goodsName;
                        $obj->oldsalePrice = $val->salePrice;
                        $obj->price         = $val->marketPrice;
                    }else{
                        $obj->creator       = 'system';
                        $obj->product_code = $val->product_code;
                        $obj->goodsName    = $val->goodsName;
                        $obj->oldsalePrice = $val->salePrice;
                        $obj->price         = $val->marketPrice;
                    }
                    $this->dbca->save($obj);
                }
                $result =  array('code'=>200, 'message' => '本地商品信息更新成功');
            }catch(Exception $e){
                error_log( $e->getMessage() );
                echo json_encode( array('message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
                return;
            }
        }
        return $result;
    }

    public function getImgUrl($product_code){

        $result = $this->dbca->stmt_query('SELECT * FROM goods_list_edit gle INNER JOIN goods_picture gp ON gle.postID = gp.postID WHERE gle.product_code = '.$product_code.'  AND gp.sortOrder = 1');

        return $result;
    }

    /**
     * 历史价格查询
     * @param $arg_array
     * @return array|null
     */
    public function searchPriceHistoryList(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //宝贝编码
        if( isset($arg_array['product_code']) && !empty($arg_array['product_code'])){
            $sql .= ' AND 3ph.product_code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['product_code'];
        }

        //宝贝名称
        if( isset($arg_array['product_name']) && !empty($arg_array['product_name'])){
            $sql .= ' AND 3ph.product_name like ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['product_name'].'%';
        }

        //店铺
        if( isset($arg_array['shopID']) && !empty($arg_array['shopID'])){
            $sql .= ' AND 3ph.shopID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['shopID'];
        }

        //下载时间
        if( isset($arg_array['startDate']) && !empty($arg_array['startDate'])){

            $arg_array['startDate'] = $arg_array['startDate'].' 00:00:00';
            $sql .= ' AND 3ph.createTime >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        if( isset($arg_array['endDate']) && !empty($arg_array['endDate'])){

            $arg_array['endDate'] = $arg_array['endDate'].' 23:59:59';
            $sql .= ' AND 3ph.createTime <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }



        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM `3rd_price_history` 3ph LEFT JOIN `3rd_shop` 3s on 3ph.shopID = 3s.shopID  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT 3ph.*,3s.title FROM `3rd_price_history` 3ph LEFT JOIN `3rd_shop` 3s on 3ph.shopID = 3s.shopID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'createTime' => $item->createTime,                //商户ID
                        'product_code' => $item->product_code,         	  //商户名称
                        'product_name' => $item->product_name,
                        'salePrice' => $item->salePrice,
                    	'goodsCode' => $item->goodsCode,
                    	'stockCount' => $item->stockCount,
                        'shopID' => $item->shopID,
                        'shopName' => $item->title
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

   
	/**
	 * 保存退换货公用方法
	 *
	 * @param unknown_type $shopID
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
    public function saveRefund($shopID , $arg_array){

        $refundGoods  = isset($arg_array['goods']) ? $arg_array['goods'] : array();            //退货商品
        $refundDetail = isset($arg_array['detail']) ? $arg_array['detail'] : array() ;         //退货信息
        
        //参数检查
		if(!isset($shopID , $refundDetail['refundID'] , $refundDetail['orderId'] , $refundDetail['refundStatus'])){
			return array('code' => 400 , 'message' => '参数错误') ;
		}
		
		//是否退货
		$returnFlg = isset($refundDetail['returnFlg'])? $refundDetail['returnFlg'] : 0;
		
		//保存退换货列表信息
        $master_refund = new entity('3rd_master_refund');
        $master_refund->refundID = $refundDetail['refundID'];
        $master_refund->shopID   = $shopID;
        if(!$this->dbca->fetch($master_refund)){
        	$master_refund->creator = $refundDetail['creator'];
        }
        //是否进入ERP
        $master_refund->enterErp 		= 0;
        $master_refund->returnFlg 		= $returnFlg;
        $master_refund->created 		= $refundDetail['created'];
        $master_refund->modified 		= $refundDetail['modified'];
        $master_refund->orderId 		= $refundDetail['orderId'];
        $master_refund->refundStatus 	= $refundDetail['refundStatus'];
        $master_refund->deliveryFee 	= $refundDetail['deliveryFee'];
        $master_refund->refundAmount 	= $refundDetail['refundAmount'];
        $master_refund->reasonMsg 		= $refundDetail['reasonMsg'];
        $master_refund->refundDesc 		= $refundDetail['refundDesc'];
        $master_refund->receiverName 	= isset($refundDetail['receiverName']) ? $refundDetail['receiverName'] : '' ;
        $master_refund->receiverPhone 	= isset($refundDetail['receiverPhone']) ? $refundDetail['receiverPhone'] : '';
        $master_refund->receiverAddress = isset($refundDetail['receiverAddress']) ? $refundDetail['receiverAddress'] : '';
        $master_refund->expressName 	= $refundDetail['expressName'];
        $master_refund->expressCode 	= $refundDetail['expressCode'];
        
        $this->dbca->beginTransaction() ;
        try{
	        $this->dbca->save($master_refund , '3rd');
	        
	        //删除老的退货商品信息
			$this->dbca->stmt_query('DELETE FROM `3rd_refund_goods` WHERE  shopID=? AND refundID=?' , 'is' , $shopID , $refundDetail['refundID']);
			
			//保存退货商品信息
			if($refundGoods){
		        foreach($refundGoods as &$g_l){
		            $refund_goods = new entity('3rd_refund_goods');
		            $refund_goods->refundID = $refundDetail['refundID'];
		            $refund_goods->shopID   = $shopID;
		            $refund_goods->itemId   = $g_l['itemId'];
		            $refund_goods->orderId  = $refundDetail['orderId'];
	                $refund_goods->postID 		= $g_l['postID'];
	                $refund_goods->product_code = $g_l['product_code'];
	                $refund_goods->goodsName 	= $g_l['goodsName'];
	                $refund_goods->refundNum 	= $g_l['refundNum'];
	                $refund_goods->refundAmount = $g_l['refundAmount'];
	                $this->dbca->save($refund_goods , '3rd');
		        }
			}
			
			$this->dbca->commit() ;
        }catch (Exception $e){
        	error_log($e->getMessage()) ;
        	$this->dbca->rollBack() ;
        }
    }

    /**
     * 交易退款列表查询
     */
    public function tradeRefundList(&$arg_array){
        //sql字符串
        $sql = '';
        //参数类型字符串
        $params_type = '';
        //参数值数组
        $params_array = array();

        //退货单号
        if( isset($arg_array['refundID']) && !empty($arg_array['refundID'])){
            $sql .= ' AND refundID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['refundID'];
        }

        //交易号
        if( isset($arg_array['orderId']) && !empty($arg_array['orderId'])){
            $sql .= ' AND orderId = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['orderId'];
        }

        //退货状态
        if( isset($arg_array['refundStatus']) && !empty($arg_array['refundStatus'])){
            $sql .= ' AND refundStatus = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['refundStatus'];
        }

        //申请时间
        if( isset($arg_array['startDate']) && !empty($arg_array['startDate'])){
            $arg_array['startDate'] = $arg_array['startDate'].' 00:00:00';
            $sql .= ' AND created >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        if( isset($arg_array['endDate']) && !empty($arg_array['endDate'])){
            $arg_array['endDate'] = $arg_array['endDate'].' 23:59:59';
            $sql .= ' AND created <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        //店铺号
        if( isset($arg_array['shopID']) && !empty($arg_array['shopID'])){
            $sql .= ' AND shopID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['shopID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {
                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM `3rd_master_refund` ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM 3rd_master_refund ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                    	'creator' => $item->creator,                //商户ID
                        'createTime' => $item->createTime,                //商户ID
                        'refundID' => $item->refundID,          //商户名称
                        'orderId' => $item->orderId,
                        'refundStatus' => $item->refundStatus,
                        'deliveryFee' => $item->deliveryFee,
                        'refundAmount' => $item->refundAmount,
                        'reasonMsg' => $item->reasonMsg,
                        'refundDesc' => $item->refundDesc,
                        'receiverName' => $item->receiverName,
                        'receiverPhone' => $item->receiverPhone,
                        'receiverAddress' => $item->receiverAddress,
                        'expressName' => $item->expressName,
                        'expressCode' => $item->expressCode,
                        'created' => $item->created,
                        'shopID' => $item->shopID
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 交易退款明细查询
     */
    public function tradeRefundDetail(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //退货单号
        if( isset($arg_array['refundID']) && !empty($arg_array['refundID'])){
            $sql .= ' AND refundID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['refundID'];
        }

        //店铺号
        if( isset($arg_array['shopID']) && !empty($arg_array['shopID'])){
            $sql .= ' AND shopID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['shopID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM `3rd_refund_goods` ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM 3rd_refund_goods ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'createTime' => $item->createTime,                //商户ID
                        'refundID' => $item->refundID,          //商户名称
                        'orderId' => $item->orderId,
                        'itemId' => $item->itemId,
                        'postID' => $item->postID,
                        'product_code' => $item->product_code,
                        'goodsName' => $item->goodsName,
                        'refundNum' => $item->refundNum,
                        'refundAmount' => $item->refundAmount
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 获取店铺任务
     * @param $arg_array
     */
    public function getShopTaskList(&$arg_array){
        //sql字符串
        $sql = '';
        //参数类型字符串
        $params_type = '';
        //参数值数组
        $params_array = array();

        //店铺号
        if( isset($arg_array['shopID']) && !empty($arg_array['shopID'])){
            $sql .= ' AND 3li.shopID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['shopID'];
        }

        if( isset($arg_array['type']) && !empty($arg_array['type'])){
            $sql .= ' AND 3li.type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['type'];
        }

        if( isset($arg_array['uuid']) && !empty($arg_array['uuid'])){
            $sql .= ' AND 3li.uuid = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['uuid'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            $arg_array['rp'] = 0;

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {
                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count  FROM 3rd_last_info 3li LEFT JOIN 3rd_shop 3s ON 3li.shopID = 3s.shopID  ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT 3li.*,3s.title FROM 3rd_last_info 3li LEFT JOIN 3rd_shop 3s ON 3li.shopID = 3s.shopID ' . $sql;
            error_log($search_sql);
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'uuid'=> $item->uuid,
                        'modified' => $item->modified,
                        'pageIndex'=> $item->pageIndex,
                        'type' => $item->type,
                        'shopID' => $item->shopID,
                        'title'=> $item->title
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 保存店铺任务
     */
    public function shopTaskSave($arg_array){

        quanli_require('module/base/commHandler.class.php');

        $commHandler = new commHandler($this->dbca);

        if(!isset($arg_array['openShopID']) || empty($arg_array['openShopID'])){
            return array('code'=>'400','message'=>'请选择店铺');
        }

        if(!isset($arg_array['uuid']) || empty($arg_array['uuid'])){

            if(!isset($arg_array['openType']) || empty($arg_array['openType'])){
                return array('code'=>'400','message'=>'请选择类型');
            }

        }

        if(!isset($arg_array['modified']) || !$commHandler->isDate($arg_array['modified'])){
            return array('code'=>'400','message'=>'更新时间格式不正确');
        }

        if(!isset($arg_array['pageIndex']) || !$commHandler->isInteger($arg_array['pageIndex'])){
            return array('code'=>'400','message'=>'更新时间格式不正确');
        }


        try{

            $last_info = new entity('3rd_last_info');
            if(isset($arg_array['uuid']) && !empty($arg_array['uuid'])){
                $last_info->uuid = $arg_array['uuid'];
                if(!$this->dbca->fetch($last_info)){
                    return array('code'=>400,'message'=>'店铺任务不存在');
                }

                $sResult = $this->dbca->stmt_query('select * from 3rd_last_info where type=? and shopID = ? and uuid!=?','iis',$arg_array['openType'],$arg_array['openShopID'],$arg_array['uuid']);
                if($sResult){
                    return array('code'=>400,'message'=>'店铺任务重复');
                }
            }
            $last_info->type = $arg_array['openType'];
            $last_info->shopID = $arg_array['openShopID'];
            if(!isset($_REQUEST['uuid']) || empty($_REQUEST['uuid'])){
                if($this->dbca->fetch($last_info)){
                    return array('code'=>400,'message'=>'店铺任务重复');
                }
            }
            $last_info->modified = $arg_array['modified'];
            $last_info->pageIndex = $arg_array['pageIndex'];

            $this->dbca->save($last_info);

            return array('code'=>200,'message'=>'保存成功');

        }catch(Exception $e){
            error_log($e->getMessage());
            return null;
        }

    }

    /*
     * 删除店铺任务
     */
    public function deleteShopTaskList($arg_array){

        if(!isset($arg_array['uuid_array'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        try{

            foreach($arg_array['uuid_array'] as $val){
                $this->dbca->stmt_query('DELETE FROM 3rd_last_info WHERE uuid = ?','s',$val);
            }

            return array('code'=>200,'message'=>'删除成功');

        }catch(Exception $e){

            error_log($e->getMessage());
            return null;

        }

    }
    
    //保存淘宝财务对账科
    public function save_accounts($shopID , $arg_array) {
    	if(isset($arg_array['id'] , $arg_array['code'] , $arg_array['name'] , $arg_array['type'])){
	    	$save_account = new entity('3rd_taobao_accounts') ;
	    	$save_account->id 	= $arg_array['id'] ;
	    	$save_account->code = $arg_array['code'] ;
	    	$save_account->name = $arg_array['name'] ;
	    	$save_account->type = $arg_array['type'] ;
	    	$save_account->enterErp = 0 ;
	    	$save_account->shopID 	= $shopID ;
	    	$this->dbca->save($save_account) ;
    	}
    }
    
    //查询用户支付宝账务明细
    public function save_accountreport($shopID , $arg_array) {
    	
    }
    
}


